Given pseudo go code below:
type(
MyStruct struct {
AFunction func(string) ([]byte, error)
}
MyInterface interface {
AFunction(string) ([]byte, error)
}
)
func NeedThis(s string) ([]byte, error){
//relevant function stuff
}
m := &MyStruct{AFunction: NeedThis}
The problem arises that m does not satisfy the MyInterface interface; and I can somewhat see why this would be so. Is there a way to attach functions to a struct in such a way that the constructed struct satisfies an interface without actually building out defining methods on the struct? I'm having some shadowy/faulty reasoning around this, maybe help to clarify this for me or show a better way to reason through this situation.
Could you not just define a method AFunction
on MyStruct
that dispatches to the stored AFunction
function pointer? It's not ideal if you have a lot of these, but I think it does the job?
i.e. something like
func (s MyStruct) AFunction(str string) ([]byte, error) {
return s.AFunction(str)
}
edit: the above may cause the compiler to error because s.AFunction
is ambiguous, so you might have to give them (the method and the function pointer) different names, but it should give the right idea.
You can wrap it in another struct that implements the interface:
http://play.golang.org/p/AgnYAWBdUp
package main
import "fmt"
type (
MyStruct struct {
AFunction func(string) ([]byte, error)
}
MyInterface interface {
AFunction(string) ([]byte, error)
}
)
func NeedThis(s string) ([]byte, error) {
//relevant function stuff
return nil, nil
}
type Proxy struct {
*MyStruct
}
func (x *Proxy) AFunction(s string) ([]byte, error) {
return x.MyStruct.AFunction(s)
}
func main() {
m := &MyStruct{AFunction: NeedThis}
p := &Proxy{m}
_, ok := MyInterface(p).(MyInterface)
fmt.Println(ok)
}