Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system.
In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. In the zero function xPtr is a pointer to an int . * is also used to “dereference” pointer variables. Dereferencing a pointer gives us access to the value the pointer points to.
The * operator allows us to access the values held at a location in memory. Think of a book. The & operator would generate a page number, the * operator would tell you what's on a given page number. We could also think of a pointer as a trail that guides our program to a value.
Go has pointers. A pointer holds the memory address of a value. The data is stored in the memory when the program runs and each has a number- the memory address, which can be assigned to a pointer, and through which we can find the data stored in memory.
I am currently learning to program with Go language. I am having some difficulties understanding Go pointers (and my C/C++ is far away now...). In the Tour of Go #52 (http://tour.golang.org/#52) for example, I read:
type Vertex struct { X, Y float64 } func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func main() { v := &Vertex{3, 4} fmt.Println(v.Abs()) }
But if instead of
func (v *Vertex) Abs() float64 { [...] v := &Vertex{3, 4}
I wrote:
func (v Vertex) Abs() float64 { [...] v := Vertex{3, 4}
Or even:
func (v Vertex) Abs() float64 { [...] v := &Vertex{3, 4}
and vice-versa:
func (v *Vertex) Abs() float64 { [...] v := Vertex{3, 4}
I got the exact same result. Is there a difference (memory-wise, etc)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With