Go · Stage 7 – Structuring Data · Lesson 45 of 64

Pointers with Structs and Functions

Use a pointer when a function must change the original struct.

Go code

type Counter struct { Value int }

func increment(c *Counter) {
    c.Value++
}

c := Counter{}
increment(&c)
fmt.Println(c.Value)
Line-by-line explanation
  1. Counter has an integer field.
  2. The parameter type *Counter means pointer to Counter.
  3. The function changes the original field.
  4. The call passes c’s address.
  5. The changed value is displayed.
Expected output
1

This is the expected result.

Go automatically allows c.Value instead of requiring (*c).Value for struct pointers.