Take addresses and dereference pointers
Take addresses and dereference pointers
A pointer of type *T refers to a variable of type T. Use &x to obtain the address of an addressable variable x, and *p to access the variable referred to by p. The two uses of * (in a type and in an expression) have different meanings.
package main
import ( "fmt")
func main() { x := 12 var p *int = &x fmt.Println(*p) *p = 15 fmt.Println(x)}p contains a pointer value, not a second copy of x. Assignment through *p updates x. The expression &x has type *int. Reading *p produces the current int value.
Expected output:
1215Allocate a zero-valued variable
package main
import ( "fmt")
func main() { p := new(int) fmt.Println(*p) *p = 8 fmt.Println(*p) xs := []int{1, 2} q := &xs[1] *q = 9 fmt.Println(xs)}new(int) returns a pointer to a zero-valued int variable. Slice elements are addressable. A literal such as 42 is not addressable: &42 does not compile. Map entries are also not addressable. Do not confuse new(T) with make, which initializes slices, maps and channels.
Expected output:
08[1 9]Try it locally
Declare stock=7, take its address into p, then increase *p by 3. Print stock and *p.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pointers and ownership 01: Take addresses and dereference pointers
Check the lesson objective before moving on.
What is the type of &x when x is an int variable?
What does new(int) initially point to?