英文:
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论