包含结构体方法的变量

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

variable containing struct method

问题

给定以下结构体:

type A struct {
    total int
}

和以下函数:

func (a *A) add(i int, j int) (x int) {
    a.total += i + j
    return i + j
}

我想创建一个指向该函数的变量,并通过该变量调用它。我在定义包含结构体实例的变量签名方面遇到了问题。

为什么要这样做?因为我想创建一个函数指针数组,并按顺序迭代调用它们。我可以使用不同的数组来完成不同的任务,使用我的函数构建块。

以下两个示例都无法编译通过:

thisfunc func(a *A) (i int, b int) (x int)
thisfunc (a *A) func(i int, b int) (x int)

以下示例可以编译通过,但不包括结构体实例,当调用thisfunc时,缺少a - 即空指针解引用。

thisfunc func(i int, b int) (x int)

我想做类似于以下的操作:

thisfunc = a.add
b := thisfunc(1, 2)

请帮助我定义一个变量thisfunc,其签名与a.add相匹配。

英文:

Given the struct:

type A struct {
    total int
}

and the func

(a *A) add func (i int, j int) (int x) {
    a.total += i+j
    return i+j
  }

I would like to create a variable pointing to the func and invoke it via that variable. I'm having trouble defining the signature for the variable that includes the instance of the struct.

Why do this? Because I want to create an array of func pointers and iterate through it it calling them in sequence. I can have different arrays to accomplish different tasks using my func building blocks.

These two don't compile:

thisfunc func (a *A) (i int, b int) (x int)
thisfunc (a *A) func (i int, b int) (x int)

This one compiles but doesn't include the struct instance and when invoking thisfunc, a is missing - no struct instance, i.e null pointer dereference.

thisfunc func (i int, b int) (x int)

I would like to do something like this:

thisfunc = a.add
b := thisfunc(1,2)

Please help me define a variable thisfunc whose signature matches a.add.

答案1

得分: 3

我认为你要找的是"方法值"(Method Values)。

给定类型A

type A struct {
    total int
}

func (a *A) add(i int, j int) int {
    a.total += i + j
    return i + j
}

虽然(*A).add方法表达式在技术上具有以下签名:

func(*A, int, int)

但你可以将add方法的值用作具有以下签名的函数:

func(int, int)

可以这样赋值:

var thisfunc func(int, int) int

a := A{}
thisfunc = a.add
thisfunc(3, 4)

你可以在这里查看示例代码。

英文:

I think what you're looking for are "Method Values"

Given type A:

type A struct {
	total int
}

func (a *A) add(i int, j int) int {
	a.total += i + j
	return i + j
}

While the method expression for (*A).add technically has a signature of

func(*A, int, int)

You can use the value of the add method as a function with the signature

func(int int)

Which can be assigned like so:

var thisfunc func(int, int) int

a := A{}
thisfunc = a.add
thisfunc(3, 4)

http://play.golang.org/p/_3WztPbL__

huangapple
  • 本文由 发表于 2015年12月30日 02:04:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/34516483.html
匿名

发表评论

匿名网友

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

确定