Home > Backend Development > Golang > Why Do Some Go Struct Setters Fail to Modify the Original Struct?

Why Do Some Go Struct Setters Fail to Modify the Original Struct?

Susan Sarandon
Release: 2025-01-02 17:19:42
Original
525 people have browsed it

Why Do Some Go Struct Setters Fail to Modify the Original Struct?

Understanding Setter Behavior for Structs

This article addresses a common misunderstanding encountered when using setter functions for struct types in Go. Despite using a setter function, a struct's value remains unchanged, while a pointer setter function successfully modifies the struct.

Setters Without Pointers

When a struct is passed by value to a function, a copy of the struct is created within the function. As a result, any modifications made to the copied struct within the function are not reflected in the original struct outside the function. This behavior is demonstrated in the following code:

type T struct { Val string }

func (t T) SetVal(s string) {
    t.Val = s
}
Copy after login

In this example, the SetVal function is defined as a method of T without a pointer receiver. When you call SetVal on a struct v, a copy of v is created within the function, and any changes made to the copy do not affect the original struct v. This is because passing a value by value creates a completely new object.

Setters With Pointers

Conversely, when a struct is passed by reference using a pointer receiver, the function receives a pointer to the original struct, enabling modifications to the actual struct outside the function. This behavior is illustrated in the following code:

func (t *T) SetVal2(s string) {
    (*t).Val = s
}
Copy after login

In this example, SetVal2 is defined as a method of T with a pointer receiver. When you call SetVal2 on a struct pointer, the function receives a pointer to the original struct, and any changes made to the struct within the function affect the original struct outside the function. This is because passing a pointer by reference shares the address of the same object.

Conclusion

The distinction between passing a struct by value and passing a struct pointer as an argument is crucial when understanding the behavior of setter functions for structs in Go. By recognizing the difference, you can effectively modify structs through setter functions as intended.

The above is the detailed content of Why Do Some Go Struct Setters Fail to Modify the Original Struct?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template