1
0
Fork 0
pr3-sose2026-fork/go/01-basics/07-pointers.go

30 lines
703 B
Go

package main
import "fmt"
// A pointer holds the memory address of a value. The type *T is a pointer to a T value. Its zero value is nil.
func zeroval(ival int) {
ival = 0
}
// To change the actual value that a pointer points to, we need to dereference the pointer.
func zeroptr(iptr *int) {
*iptr = 0
}
func main() {
i := 1
fmt.Println("initial:", i)
// zeroval will get a copy of i, so the original i is not affected.
zeroval(i)
fmt.Println("zeroval:", i)
// zeroptr will get a pointer to i, so it can change the value of i through the pointer.
zeroptr(&i)
fmt.Println("zeroptr:", i)
// We can also use the & operator to get the pointer of a variable.
fmt.Println("pointer:", &i)
}