Pointers
package main
import "fmt"
// zeroval takes an integer parameter by value and sets it to 0
func zeroval(ival int) {
ival = 0
}
// zeroptr takes a pointer to an integer as a parameter and sets the value it points to (dereferencing) to 0
func zeroptr(iptr *int) {
*iptr = 0
}
func main() {
// Declare and initialize an integer variable i with the value 1
i := 1
fmt.Println("initial:", i)
// Call zeroval with the value of i, but it won't change the original i
zeroval(i)
fmt.Println("zeroval:", i) // Output: zeroval: 1
// Call zeroptr with the address (pointer) of i, it will change the value of i through the pointer
zeroptr(&i)
fmt.Println("zeroptr:", i) // Output: zeroptr: 0
// Print the memory address of i using the & operator
fmt.Println("pointer:", &i)
}Output
Last updated