Sobes.tech
Junior — Middle

What is the difference between using a pointer to a structure and passing the structure itself in a method in Go?

sobes.tech AI

Answer from AI

In Go, methods can have a receiver either by value (struct) or by pointer to a struct. The difference between them:

  • Receiver by value: the method gets a copy of the struct. Changes inside the method will not affect the original object. Suitable if the struct is small and no need to modify its state.

  • Receiver by pointer: the method gets a pointer to the struct, can modify the fields of the original object. Also more efficient for large structs, as the entire struct is not copied.

Example:

package main
import "fmt"

type User struct {
    Name string
}

func (u User) RenameValue(newName string) {
    u.Name = newName // only the copy will change
}

func (u *User) RenamePointer(newName string) {
    u.Name = newName // the original will change
}

func main() {
    user := User{Name: "Alice"}
    user.RenameValue("Bob")
    fmt.Println(user.Name) // Alice

    user.RenamePointer("Bob")
    fmt.Println(user.Name) // Bob
}

The choice depends on the task: if you need to change the object's state — use a pointer; if not — you can use a value.