Interface Implementation in Go: Function Types Returning Structs
When working with Go, it is common to encounter situations where a function returns a struct that implements an interface. However, you may face an error similar to "cannot use [function] as type [interface] in field value" when attempting to assign the function to a field that expects an instance of the interface.
To understand this error, it is crucial to clarify that a function that returns a pointer to a struct (struct) does not automatically implement an interface defined for that struct. In other words, struct and struct are distinct types in Go.
In the given example, the function getInstance is expected to return a value of type myInterface, which is a description of behavior (interface) rather than a specific implementation (struct). However, getInstance returns a pointer to the myStruct implementation (*myStruct), which is not type-compatible with myInterface.
To resolve this issue, you need to modify getInstance to return an instance of the myStruct struct, as seen in the corrected code below:
package main import "fmt" func main() { var function func() myInterface function = getInstance newSomething := function() newSomething.doSomething() } type myInterface interface { doSomething() } type myStruct struct{} func (m *myStruct) doSomething() { fmt.Println("doing something") } func getInstance() myInterface { return &myStruct{} }
This modification ensures that myStruct implements the myInterface interface, and the getInstance function returns the correct type.
While the above approach works, Go has proposed a language change to automatically convert a function returning a concrete type to a function returning an interface if the concrete type implements the interface. However, this proposal was rejected due to potential performance and safety concerns.
The above is the detailed content of Why Doesn't a Go Function Returning a Struct Pointer Automatically Implement an Interface?. For more information, please follow other related articles on the PHP Chinese website!