int là pointer type, &x lấy address, p dereference.
Go không có pointer arithmetic như C. nil pointer gây panic.
go
x := 42
p := &x // p là *int, trỏ đến x
fmt.Println(*p) // 42 — dereference
*p = 100
fmt.Println(x) // 100 — modify qua pointer
// Dùng pointer để modify tham số
func increment(n *int) {
*n++
}
increment(&x)
// Pointer receiver — modify struct gốc
func (u *User) SetAge(age int) {
u.Age = age
}Dùng pointer khi:
- muốn modify giá trị gốc.
- struct lớn (tránh copy).
- method cần modify receiver
int is a pointer type, &x gets the address, p dereferences it.
- Go has no pointer arithmetic.
- Dereferencing a nil pointer causes a panic.
go
x := 42
p := &x // p is *int, points to x
fmt.Println(*p) // 42 — dereference
*p = 100
fmt.Println(x) // 100 — modified via pointer
// Use pointer to mutate a parameter
func increment(n *int) {
*n++
}
increment(&x)
// Pointer receiver — mutates the original struct
func (u *User) SetAge(age int) {
u.Age = age
}Use pointers when:
- you need to modify the original value;
- working with large structs (avoid copying);
- a method needs to mutate its receiver