带接收器的函数类型

mac*_*lir 1 go type-alias

如何将带有接收器的函数声明为类型?

我以为我可以执行以下操作,但它抱怨语法错误:

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 {
    ...
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 6

您可以定义一个函数类型,它将接收者作为它的第一个参数(本质上就是方法)。

type myFunc func(*State, Blah) error
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用方法表达式来创建该类型的值:

type Blah struct{}
type State struct{}

func (s *State) myF(Blah) error { return nil }

var f myFunc = (*State).myF
Run Code Online (Sandbox Code Playgroud)

如果 M 在类型 T 的方法集中,则 TM 是一个可作为常规函数调用的函数,该函数具有与 M 相同的参数,并以作为方法接收者的附加参数为前缀。

[...]

表达方式

T.Mv
Run Code Online (Sandbox Code Playgroud)

产生一个等价于 Mv 的函数,但它的第一个参数是显式接收器;它有签名

func(tv T, a int) int
Run Code Online (Sandbox Code Playgroud)