Sobes.tech
Junior

What does the asterisk (*) mean for a receiver in Go?

sobes.tech AI

Answer from AI

A star * in a receiver in Go indicates that the method works with a pointer to the struct instance, rather than a copy of it.

The consequences of this:

  1. State modification: The method can modify the fields of the struct instance itself, not just its copy.
  2. Performance: Passing a pointer is usually faster than copying large structs, especially when called in a loop.
  3. Interface consistency: When implementing an interface, if one of the methods needs to modify the struct's state (uses a pointer receiver), then all methods implementing that interface should use a pointer receiver for that type.

Example: Modifying a struct field with a pointer receiver:

type Counter struct {
	Value int
}

// Increment modifies Value directly, as the receiver is a pointer
func (c *Counter) Increment() {
	c.Value++
}

// GetValue works with a copy of Counter (does not modify),
// but for consistency with Increment, which changes state,
// a pointer receiver is often used in such cases.
func (c *Counter) GetValue() int {
	return c.Value
}

Example without a pointer receiver:

type Counter struct {
	Value int
}

// IncrementCopy works with a copy of Counter, the original Value will not change
func (c Counter) IncrementCopy() {
	c.Value++
}