Home > Backend Development > Golang > Why Doesn't My Go Method Modify the Instance Value Unless I Use a Pointer Receiver?

Why Doesn't My Go Method Modify the Instance Value Unless I Use a Pointer Receiver?

Mary-Kate Olsen
Release: 2024-12-08 22:11:12
Original
298 people have browsed it

Why Doesn't My Go Method Modify the Instance Value Unless I Use a Pointer Receiver?

Golang Method with Pointer Receiver

When attempting to modify the value of an instance through a method, it's crucial to understand the concept of pointer receivers. In this example, the SetSomeField method is not working as expected because its receiver is not of pointer type.

To rectify this, we modify the SetSomeField method to accept a pointer receiver as follows:

func (i *Implementation) SetSomeField(newValue string) {
    ...
}
Copy after login

However, this change introduces a new problem: the struct no longer implements the interface because the GetSomeField method still has a value receiver.

The solution lies in using a pointer to the struct when implementing the interface. By doing so, we enable the method to modify the actual instance without creating a copy. Here's the modified code:

type IFace interface {
    SetSomeField(newValue string)
    GetSomeField() string
}

type Implementation struct {
    someField string
}

func (i *Implementation) GetSomeField() string {
    return i.someField
}

func (i *Implementation) SetSomeField(newValue string) {
    i.someField = newValue
}

func Create() *Implementation {
    return &Implementation{someField: "Hello"}
}

func main() {
    var a IFace
    a = Create()
    a.SetSomeField("World")
    fmt.Println(a.GetSomeField())
}
Copy after login

In this updated code, the Create function returns a pointer to the Implementation struct, which implements the IFace interface. Consequently, the a variable of type IFace can refer to the pointer to the Implementation struct, allowing the SetSomeField method to modify its value.

The above is the detailed content of Why Doesn't My Go Method Modify the Instance Value Unless I Use a Pointer Receiver?. 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