给定结构:
type A struct {
total int
}
和函数
(a *A) add func (i int, j int) (int x) {
a.total += i+j
return i+j
}
我想创建一个指向函数的变量并通过该变量调用它。我在为包含结构实例的变量定义签名时遇到问题。
为什么要这样做?因为我想创建一个 func 指针数组并遍历它,所以它按顺序调用它们。我可以使用不同的数组来使用我的 func 构建 block 来完成不同的任务。
这两个不编译:
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)
请帮我定义一个签名匹配a.add的变量thisfunc。
最佳答案
我想你要找的是"Method Values"
给定类型A
:
type A struct {
total int
}
func (a *A) add(i int, j int) int {
a.total += i + j
return i + j
}
虽然 method expression (*A).add
技术上有一个签名
func(*A, int, int)
您可以将 add
方法的值用作带有签名的函数
func(int int)
可以这样赋值:
var thisfunc func(int, int) int
a := A{}
thisfunc = a.add
thisfunc(3, 4)
关于go - 包含结构方法的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34516483/