Go supports pointers, allowing you to pass references to values and records within your program. So, what is a pointer and how to use? Pointer is a variable which store address of other variable
I have a variable i with value is 1
p is a pointer with value is address of i. So, p is not 1, that is only address in your computer on memory
i := 1
p := &i
fmt.Println("value of i", i)
fmt.Println("address of i on memory", p)
fmt.Println("value of i from p", *p)
Here, I have 2 functions
1st use param as int
2nd use param as pointer int
In main function, I call 2 function and print result. 1st function not change value of i because function only process on copy of i. But, 2nd function change value of i because I ask by address of i and want to change value in that address
func setToZero1(data int) {
i = 0
}
function setToZero2(data *int){
*data = 0
}
func main() {
i := 1
setToZero1(i)
fmt.Println(i)
setToZero2(&i)
fmt.Println(i)
}
View on github