How can I declare a function with a receiver as a type?
I thought I would be able to the following, but it complains about syntax error:
type myFunc func(s *State) (blah Blah) err
func main() {
b := &Blah{}
s := &State{}
var f = myF
s.f(b)
}
func (s *State) myF(blah Blah) err {
...
}
You can define a function type that takes the receiver as its first argument (that's essentially what methods are).
type myFunc func(*State, Blah) error
You can then use a method expression to create a value of that type:
type Blah struct{}
type State struct{}
func (s *State) myF(Blah) error { return nil }
var f myFunc = (*State).myF
If M is in the method set of type T, T.M is a function that is callable as a regular function with the same arguments as M prefixed by an additional argument that is the receiver of the method.
[...]
The expression
T.Mv
yields a function equivalent to Mv but with an explicit receiver as its first argument; it has signature
func(tv T, a int) int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With