Go Function Types that Return Structs Inside Interfaces
In Go, it is common to use interfaces to define the behavior of structs. However, when working with functions that return structs that implement interfaces, you may encounter type-safety errors.
Understanding the Issue
Let's examine the code example you provided:
package expensive type myStruct struct { ... } // Struct with time-consuming methods func CreateInstance() *myStruct { ... } // Expensive factory function
package main import "expensive" type myInterface interface { DoSomething() } type structToConstruct struct { factoryFunction func() myInterface } func (s *structToConstruct) performAction() { instance := s.factoryFunction(); instance.DoSomething() }
Here, you defined a factory function CreateInstance that returns a *myStruct. You then created an interface myInterface that *myStruct implements. However, you assigned the factory function to a field in structToConstruct that expects a function returning myInterface, causing the compilation error.
Solving the Issue
To resolve this, you have two options:
wrapper := func() myInterface { return expensive.CreateInstance() } thing := structToConstruct{wrapper}
func CreateInstance() myInterface { return &myStruct{} }
Why Option 1 Works
In Option 1, the wrapper function converts the result of CreateInstance to myInterface before assigning it to factoryFunction. This satisfies the type signature of structToConstruct because the wrapper function matches the expected function type.
Why Option 2 Requires Proposal 12754
In Option 2, if you attempt to directly assign CreateInstance to factoryFunction, Go will complain because CreateInstance returns a structured pointer, not an interface. Proposal 12754 suggests extending the language to support such assignments, but it was ultimately rejected.
The above is the detailed content of How Can I Handle Go Functions Returning Structs Implementing Interfaces?. For more information, please follow other related articles on the PHP Chinese website!