Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function type with a receiver

Tags:

go

type-alias

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 {
    ...
}
like image 512
maclir Avatar asked Jan 03 '23 00:01

maclir


1 Answers

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
like image 132
Peter Avatar answered Jan 05 '23 15:01

Peter