Go Pointer : Introduction
What I learned today about Go Pointer from Learning Go : Chapter 6 book :
Pointer : a variable that holds the location in memory where the value is stored.
Every pointer, always take the same number of memory locations (whether it is 4byte or 8byte).
Zero value of a pointer is nil.
Data type that implemented with pointers : slice, maps, functions, channels, interfaces
Go has a garbage collector.
Pointer arithmetic is not allowed in Go.
The & : returns the address where the value is stored.
The * : returns the pointed-to value.
The program will panic if we attempt dereference a nil pointer.
var x *int
fmt.Println(*x) // panics
newfunction creates a pointer variable -> returns a pointer to a zero-value.
var x = new(int)
fmt.Println(*x) // prints 0
- We can create a pointer instance to struct by an &.
x := &Foo{}
- BUT we can't use an & before primitive literal (numbers, booleans, strings) or constant. BCS they don't have memory address. They only exist at compile time.
type Person struct {
FirstName string
LastName *string
}
p := person{
FirstName: "Pat",
LastName: &"Peterson", // This line won't compile
}
- Thus, we can introduce a variable to hold the constant value.
lastName := "Peterson"
p := person{
FirstName: "Pat",
LastName: &lastName,
}