Home >Backend Development >Golang >Why Can\'t Go Interfaces Directly Support Setter Methods, and How Can This Be Worked Around?
Polymorphism in Go: A Closer Look at Interface Methods and Pointer Receivers
In Go, polymorphism is not natively supported, but it can be achieved using interfaces. This introduces a common question: why aren't setter methods allowed for interfaces?
As demonstrated in the code provided, when the setter method is defined as a value receiver, changes made within the function are lost when it exits. Modifying the receiver to a pointer receiver allows for permanent changes, but it raises a compilation error.
To address this, Go provides a workaround. The corrected code modifies the receiver of the setter method to be a pointer. This enables the function to modify the underlying data structure and retain the changes. The modified code uses an interface, ensuring that the pointer receiver method is accessible through the interface.
package main import "fmt" type MyInterfacer interface { Get() int Set(i int) } type MyStruct struct { data int } func (this *MyStruct) Get() int { return this.data } func (this *MyStruct) Set(i int) { this.data = i } func main() { s := &MyStruct{123} fmt.Println(s.Get()) s.Set(456) fmt.Println(s.Get()) var mi MyInterfacer = s mi.Set(789) fmt.Println(mi.Get()) }
While this is not strictly polymorphism, it effectively achieves a similar result by using interfaces and pointer receivers. The code can be used to set properties through an interface, cleanly encapsulating data and operations.
The above is the detailed content of Why Can\'t Go Interfaces Directly Support Setter Methods, and How Can This Be Worked Around?. For more information, please follow other related articles on the PHP Chinese website!