go - 包含结构方法的变量

标签 go

给定结构:

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)

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

关于go - 包含结构方法的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34516483/

相关文章:

git - 无法访问 Go 库

mongodb - 在对象的生命周期内保持 MongoDB session 打开是否明智?

go - 被嵌入在golang结构中的接口(interface)所困惑

go - 无法在 Golang 中导入本地模块

go - micro_out : protoc-gen-micro: Plugin failed

amazon-web-services - 尝试在本地访问 DynamoDB 时超时

go - Golang atomic.StorePointer(...)表现异常

使用 Golang 的 HTTP 基本身份验证

json - 正确创建 JSON 文件并从中读取

去 GC 停止我的 goroutine?