Sobes.tech
Junior — Middle

What is the function of the receiver object with a pointer to a star?

sobes.tech AI

Answer from AI

In Go, an object receiver with a pointer (for example, func (r *ReceiverType) Method()) allows the method to modify the state of the object that the receiver points to. Using a pointer instead of a value provides the following advantages:

  • Allows modifying the fields of the struct within the method.
  • Avoids copying large structs when calling the method, which improves performance.
  • Ensures consistency if other methods accept a pointer.

Example:

type Counter struct {
    count int
}

func (c *Counter) Increment() {
    c.count++  // modify the struct's field through the pointer
}

func main() {
    c := Counter{}
    c.Increment()
    fmt.Println(c.count)  // Will output 1
}