ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Go (Golang) Tutorial• 7 min read

Structs, Methods & Value vs Pointer Receivers

type Struct, composition over inheritance, and (s *Student) receivers

Go does not have classes or inheritance. Instead, data is modeled using struct types, and behavior is attached using Methods with Value or Pointer receivers.

Value Receivers vs Pointer Receivers

Value Receiver (func (u User) Display()): Operates on a copy of the struct. Cannot modify original fields.

Pointer Receiver (func (u *User) UpdateAge(newAge int)): Operates directly on the original struct in memory. Essential when mutating state or avoiding copies of large structs.

Composition: Embed structs inside other structs to reuse fields and methods without inheritance hierarchies.

Pointer Receiver Method in Go
package main

import "fmt"

type Student struct {
    Name string
    XP   int
}

// Pointer receiver (*Student) mutates the original instance!
func (s *Student) AwardXP(points int) {
    s.XP += points
}

func main() {
    coder := Student{Name: "Ada", XP: 100}
    coder.AwardXP(50)
    fmt.Printf("%s has %d XP\n", coder.Name, coder.XP) // 150
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

When should a Go method use a Pointer Receiver `(s *MyStruct)` instead of a Value Receiver `(s MyStruct)`?