Sobes.tech
Junior

What does the asterisk mean in a receiver in Go?

sobes.tech AI

Answer from AI

A star (*) next to a receiver in Go indicates that the method is called on a pointer to an instance of the type, rather than on the value of the type.

The main implications of this:

  1. State modification: A method with a pointer receiver can modify the fields of the structure (or other type) it points to. Without the star, the method works with a copy of the value, and changes inside the method do not affect the original.
  2. Performance: Passing a pointer can be more efficient than passing a large structure by value, as only the address is passed, not the entire structure.
  3. Nil values: Methods with pointer receivers can be called on nil pointers, which can be useful for graceful handling of such cases.

Example:

package main

import "fmt"

type Counter struct {
	value int
}

// Method with value receiver: does not change the original Counter
func (c Counter) IncrementByValue() {
	c.value++ // Only the copy is changed
}

// Method with pointer receiver: changes the original Counter
func (c *Counter) IncrementByPointer() {
	c.value++ // The original value is changed
}

func main() {
	c1 := Counter{value: 0}
	c1.IncrementByValue()
	fmt.Println("Value after IncrementByValue:", c1.value) // Will print 0

	c2 := Counter{value: 0}
	c2.IncrementByPointer()
	fmt.Println("Value after IncrementByPointer:", c2.value) // Will print 1
}