Back to Blog

Methods, Value vs Pointer Receivers Explained | Learn Golang #16

Sandy LaneSandy Lane

Video: Methods, Value vs Pointer Receivers Explained | Learn Golang #16 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Methods, Value vs Pointer Receivers Explained in Go

In Go, methods are functions with a special receiver argument, allowing you to associate behavior with types. This guide explains how to define methods using value and pointer receivers, when to use each, and how to add methods not only to structs but also to custom types.

Code

package main

import "fmt"

// Define a struct type
type Rectangle struct {
  Width, Height int
}

// Method with a value receiver: operates on a copy of Rectangle
func (r Rectangle) Area() int {
  return r.Width * r.Height
}

// Method with a pointer receiver: can modify the original Rectangle
func (r *Rectangle) Scale(factor int) {
  r.Width *= factor
  r.Height *= factor
}

// Custom type based on int
type MyInt int

// Method on custom type
func (m MyInt) IsPositive() bool {
  return m > 0
}

func main() {
  rect := Rectangle{Width: 5, Height: 10}
  fmt.Println("Area:", rect.Area()) // Calls value receiver method

  rect.Scale(2)                      // Calls pointer receiver method to modify rect
  fmt.Println("Scaled Area:", rect.Area())

  var num MyInt = 7
  fmt.Println("Is num positive?", num.IsPositive())
}

Key Points

  • Methods in Go are functions with receivers, associating behavior with types like structs or custom types.
  • Value receivers get a copy of the value, so changes inside the method do not affect the original object.
  • Pointer receivers receive a pointer to the value, allowing methods to modify the original data.
  • Use pointer receivers when your method needs to modify the receiver or when copying the value is expensive.
  • Methods can be defined on any named type, including custom types based on primitives, not just structs.