指针保存值的内存地址,而不是值本身。Go 有指针(像 C 一样),但保持它们简单安全——没有指针算术,垃圾回收器管理内存。它们用于高效地共享和修改数据。
两个操作符:& 和 *
go
x := 42
p := &x // & = "address of" → p is a *int (pointer to x)
fmt.Println(p)
fmt.Println(*p)
*p =
fmt.Println(x)
& 获取变量的地址;*(在指针上)访问或设置它所指向的值。
// ❌ value parameter — the function gets a COPY; changes don't affect the caller
func incrementValue(n int) { n++ } // caller's variable unchanged
// ✅ pointer parameter — the function can modify the caller's variable
func incrementPointer(n *int) { *n++ }
x := 5
incrementValue(x) // x still 5
incrementPointer(&x) // x is now 6
由于 Go 按值传递参数(复制),函数只有在接收指针时才能修改调用者的数据。这是使用指针的主要原因。
type Counter struct { count int }
// pointer receiver → method can modify the struct
func (c *Counter) Increment() { c.count++ }
c := &Counter{} // a pointer to a Counter
c.Increment() // modifies it (Go auto-dereferences: (*c).count++)
指针接收者是方法改变其结构体的方式,传递结构体指针避免了复制大型结构体。
var p *int // zero value of a pointer is nil
fmt.Println(p) // <nil>
*p = 5 // 💥 PANIC: nil pointer dereference (no value to point to)
if p != nil { *p = 5 } // guard against nil
解引用 nil 指针会引发 panic——这是一个常见的运行时错误,需要防护。
✗ NO pointer arithmetic (can't do p++ to move through memory like C)
✗ NO manual free — garbage collector reclaims memory
→ Pointers are about sharing/modifying data, not low-level memory hacking
指针在 Go 中有两个主要用途:修改调用者的数据(因为 Go 按值传递,只有指针才能让函数改变原始值)和效率(传递指针避免了复制大型结构体)。
它们是带有指针接收者的方法的基础(修改结构体的标准方式),在惯用 Go 中随处可见。
理解 &/*、值与指针语义、nil 指针 panic 以及 Go 指针有意地是安全的(没有算术、GC 管理)——专注于共享和修改而非 C 风格的内存操作——是编写正确高效的 Go 代码的核心知识,也是新手和面试中经常困惑的地方。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠