Question:
In Go, I have a struct in one package that implements an interface. In another dependent package, I want to create a fake implementation of this struct for testing purposes. However, Go is complaining about type safety when I try to assign a function returning a struct that implements the interface to a variable of that interface.
Architecture:
// Package expensive type myStruct struct{} func (m *myStruct) DoSomething() {...} func (m *myStruct) DoSomethingElse() {...} func CreateInstance() *myStruct {...} // Expensive to call // Package main type myInterface interface { DoSomething() } type structToConstruct struct { factoryFunction func() myInterface } func (s *structToConstruct) performAction() {...}
Error:
"cannot use expensive.CreateInstance (type func() *expensive.myStruct) as type func() myInterface in field value"
Answer:
The issue arises because the CreateInstance function returns a *myStruct value, which differs from the func() myInterface type required by factoryFunction. To resolve this:
// Package main type myInterface interface { DoSomething() } type myStruct struct{} func (m *myStruct) DoSomething() {...} func getInstance() myInterface { return &myStruct{} }
With this modification, getInstance now returns an myInterface type, allowing it to be assigned to factoryFunction.
Additional Notes:
wrapper := func() myInterface { return expensive.CreateInstance() }
The above is the detailed content of How to Assign a Function Returning a Struct Implementing an Interface in Go?. For more information, please follow other related articles on the PHP Chinese website!