What I'm trying to do:
I have a library package which defines a few types, all implementing a given interface. Throughout the code, there are callbacks involved, and instead of writing the callback type everywhere I defined a type for it.
type Foo interface {
Bar()
}
type MyCallback func(f Foo)
type CoolFoo int
type BadFoo int
func (cf *CoolFoo) Bar(cb MyCallback) {
}
func (bf *BadFoo) Bar(cb MyCallback) {
}
Then later from client code using that library, I want to call using callbacks. If I call it by using the interface type it works:
cf := &CoolFoo{}
cf.Bar(func(f packageName.Foo) {
})
But I would rather have more self documenting code, and proper type hinting in my IDE, so I try to call it using the implementor type, such as this:
cf := &CoolFoo{}
cf.Bar(func(f packageName.CoolFoo) {
})
Which fails to compile, with the error:
cannot use func literal (type func(packageName.CoolFoo)) as type packageName.MyCallback in argument to cf.Bar
Is it not possible, or am I making some dummy mistake ? I'm not very experienced in go dev, and I've tried looking around, but couldn't find the solution here.
What I've found is passing it as a Foo or an interface{} and then casting in the callback to what I want, but I would like to avoid it as it feels messy
Thanks for any help