0%

GO_Learning_Fundamental_Pointer

Definition

Every var has memory address and value, Pointer is the variable that store the address as its value. In Go language, & means toke address operation, while * means get the value from address operation. Pointer is a kind of variable that store the address of corresponding variable.

Syntax

1
2
3
ptr := &v
// v: token address variable, type T
// ptr: pointer variable, named as the pointer of T, type: *T

Example:

1
2
3
4
5
6
7
func main() {
a := 10
b := &a
fmt.Printf("a:%d ptr:%p\n", a, &a) // a:10 ptr:0xc00001a078
fmt.Printf("b:%p type:%T\n", b, b) // b:0xc00001a078 type:*int
fmt.Println(&b) // 0xc00000e018
}

image-20211004001357927

Token Address: & get pointer

Get the value of pointer: * get value of pointer infered

Pointers let us point to some values and then let us change them.

Go copies values when you pass them to functions/methods, so if you’re writing a function that needs to mutate state you’ll need it to take a pointer to the thing you want to change.

The fact that Go takes a copy of values is useful a lot of the time but sometimes you won’t want your system to make a copy of something, in which case you need to pass a reference. Examples include referencing very large data structures or things where only one instance is necessary (like database connection pools).

Pointers can be nil

When a function returns a pointer to something, you need to make sure you check if it’s nil or you might raise a runtime exception - the compiler won’t help you here.

Useful for when you want to describe a value that could be missing