在GO中,有没有一种匿名满足接口的方法?似乎没有,但这是我最大的努力.

(在Playground名中)

package main

import "fmt"

type Thing interface {
    Item() float64
    SetItem(float64)
}

func newThing() Thing {
    item := 0.0
    return struct {
        Item (func() float64)
        SetItem (func(float64))
    }{
        Item: func() float64 { return item },
        SetItem: func(x float64) { item = x },
    }
}

func main() {
    thing := newThing()
    fmt.Println("Hello, playground")
    fmt.Println(thing)
}

推荐答案

Go使用method sets来声明哪些方法属于某个类型.只有一种方法可以声明具有接收器类型(方法)的函数:

func (v T) methodName(...) ... { }

由于禁止嵌套函数,因此无法在匿名 struct 上定义方法集.

第二件不允许这样做的事情是方法是只读的.引入了Method values个,以允许在goroutine中传递和使用方法,但不能操作方法集.

相反,您可以提供一个ProtoThing并引用匿名 struct 的底层实现(on play):

type ProtoThing struct { 
    itemMethod func() float64
    setItemMethod func(float64)
}

func (t ProtoThing) Item() float64 { return t.itemMethod() }
func (t ProtoThing) SetItem(x float64) { t.setItemMethod(x) }

// ...

t := struct { ProtoThing }{}

t.itemMethod = func() float64 { return 2.0 }
t.setItemMethod = func(x float64) { item = x }

这是可行的,因为通过嵌入ProtoThing,方法集是继承的.因此,匿名 struct 也满足Thing接口.

Go相关问答推荐

如何防止程序B存档/删除围棋中程序A当前打开的文件?

如何在 Chi Router 的受保护路由下提供静态文件(尤其是图像)?

从带有嵌套括号的字符串中提取值

Go 中带有回调的 MiniDumpWriteDump

Go-如何在递归函数中关闭通道

如何解决我的 Go 聊天应用程序中 cookie 未在本地主机端口之间传输的问题?

如何使用 sync.WaitGroup 来执行所有的 goroutine?

golang中如何声明多个接口约束?

Neptune 在连接到启用 IAM 的 Neptune 实例时抛出握手错误错误

Golang 中具体类型的错误片段

有没有办法约束(通用)类型参数?

函数实现接口时的模式名称是什么?

将 big.Int 转换为 [2]int64,反之亦然和二进制补码

如何从 Go 1.18 中的单个方法返回两种不同的具体类型?

Go 使用 struct 作为接口而不实现所有方法

如何在眼镜蛇(golang)中将标志作为参数传递?

try 执行`go test ./... -v`时,Golang中有没有办法设置标志

Go 赋值涉及到自定义类型的指针

从 map 返回空数组而不是空字符串数组

Go 泛型是否与 LINQ to Objects 等效?