Pointers and References
people who have a Java programming background like me, may be have a feeling that it is easy to understand the concept of pointers and references , but have a hard time to remember & and * 's operations.
[ & ] - a memory address marker
Computer store data in memory , and each memory has an address.
package main
import (
"fmt"
)
func main() {
var data int = 5;
fmt.Printf("Memory Address: %p and Data: %d ", &data , data);
}
[output]
Memory Address: 0x10328000 and Data: 5
Program exited.
So & is a address marker.
[ * ] - a pointer marker
If we wanted to store the address of a piece of data into a variable instead of using it directly as above , we can do it this way ,
package main
import(
"fmt"
)
func main() {
var i int = 7
var p *int
p = &i
fmt.Println("i : " , i)
fmt.Println("memory address of i : ", &i)
fmt.Println("p : " , p)
fmt.Println("*p : " , *p)
}
[output]
i : 7
memory address of i : 0x10328000
p : 0x10328000
*p : 7
Program exited.
So what is a pointer ?
A pointer look like "special data type" in which the memory address of another value is stored.
var p *int
We called p a pointer ( an integer pointer ) , and *int a "special data type" , because it looks nothing like any builtin data type - bool , int8 , int16 ...etc , but it is in a position of type of a variable declaration ( l don't know whether it is a TYPE internally ).
What about *p ? the asterisk in front of p , which make *p equal to 7 ? Oh .. we called the asterisk a pointer dereference operator .
p ( &i ) is a pointer , and *p is the data it pointing to.
But can we get the address back by using **p or *( p ) , like we do maths , (-5)(-5) = +25 ?
No , it is not the right syntax.
package main
import(
"fmt"
)
func main() {
var i int = 7
var p *int
p = &i
fmt.Println(" **p : " , **p) // both cannot be compile
fmt.Println(" *(*p) : " , *(*p))
}
[output]
prog.go:12: invalid indirect of *p (type int)
prog.go:13: invalid indirect of *p (type int)
[process exited with non-zero status]
Program exited.
Show Me More Pointers ?
Using new() to create pointer :
package main
import "fmt"
func main() {
c := new(int)
fmt.Println("c -> ", c)
}
[output]
c -> 0x10328000
--