Pointers to structs

Struct fields can be accessed through a struct pointer.

To access the field X of a struct when we have the struct pointer p we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.

struct-pointers.go

  1. package main
  2. import "fmt"
  3. type Vertex struct {
  4. X int
  5. Y int
  6. }
  7. func main() {
  8. v := Vertex{1, 2}
  9. p := &v
  10. p.X = 1e9
  11. fmt.Println(v)
  12. }