Sobes.tech
Intern

Why is the structure's field usually made a pointer to the structure inside a function argument rather than a value?

sobes.tech AI

Answer from AI

In Go, function arguments are passed by value, meaning they are copied. If you pass a struct by value, a copy of that struct is used inside the function, and changes to fields will not affect the original.

To modify the fields of a struct inside a function and keep those changes after the function exits, you need to pass a pointer to the struct. Then, the function will work with the original data, not a copy.

Example:

 type User struct {
    Name string
}

func changeNameByValue(u User) {
    u.Name = "Alice"
}

func changeNameByPointer(u *User) {
    u.Name = "Bob"
}

func main() {
    user := User{Name: "John"}
    changeNameByValue(user)
    fmt.Println(user.Name) // Will print "John" — the copy changed, not the original

    changeNameByPointer(&user)
    fmt.Println(user.Name) // Will print "Bob" — the original was changed
}

Thus, a pointer is needed to modify the original struct, not its copy.

Why is the structure's field usually made a pointer… - sobes.tech