方法类型定义的语法辅助?

huangapple go评论79阅读模式
英文:

Syntax assist for method type definition?

问题

抱歉,如果这显而易见的话;我对Golang相对较新。

我需要将一个带有指针接收器的函数作为参数传递给一个方法,并将该函数指针存储在其他结构体中等等。

没有接收器时,这很简单。对于这样的函数...

func Sample(ctx *Context, arg int) (err error)

...我可以使用以下语法创建一个函数类型...

type SampleFunc func(ctx *Context, arg int) (err error)

...但是对于带有接收器的函数,例如...

func (ctx *Context) Sample(arg int) (err error)

...类型定义的语法是什么?我尝试了...

type SampleFunc func(ctx *Context) (arg int) (err error)

...但是这只会产生syntax error: unexpected ( after top level declaration的错误。

谢谢你的建议。

英文:

Apologies if this is obvious; relatively new to Golang.

I need to pass a function with a pointer receiver as an argument to a method, and to store that function pointer in other structs, etc.

Without a receiver, this is straightforward. For a function such as...

func Sample(ctx *Context, arg int) (err error)

...I can create a function type by using the syntax...

type SampleFunc func (ctx *Context, arg int) (err error)

...but for a function with a receiver such as...

func (ctx *Context) Sample(arg int) (err error)

...what's the syntax for the type definition? I tried...

type SampleFunc func (ctx *Context) (arg int) (err error)

...but that just yields syntax error: unexpected ( after top level declaration

Thanks for your advice.

答案1

得分: 2

语法如下:

type SampleFunc func (ctx *Context, arg int) (err error)

Sample方法分配给类型为SampleFunc的变量,如下所示:

var f SampleFunc = (*Context).Sample

(*)部分对于指针接收器方法是必需的。像这样调用它:

 f(ctx, 1)

playground示例

英文:

The syntax is

type SampleFunc func (ctx *Context, arg int) (err error)

Assign the Sample method to a variable of type SampleFunc like this:

var f SampleFunc = (*Context).Sample

The (*) part is required for pointer receiver methods. Call it like this:

 f(ctx, 1)

playground example

huangapple
  • 本文由 发表于 2017年6月1日 03:59:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/44293693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定