【问题标题】:struct initialize to satisfy an interface without explicit method definition结构初始化以满足没有显式方法定义的接口
【发布时间】:2014-08-13 17:28:47
【问题描述】:

下面给出伪 go 代码:

type(
    MyStruct struct {
        AFunction  func(string) ([]byte, error)
    }

    MyInterface interface {
        AFunction(string) ([]byte, error)
    }
)

func NeedThis(s string) ([]byte, error){
    //relevant function stuff
}

m := &MyStruct{AFunction: NeedThis}

问题出现了,m不满足MyInterface接口;我有点明白为什么会这样。有没有办法将函数附加到结构上,使得构造的结构满足接口而不实际在结构上构建定义方法?我对此有一些模糊/错误的推理,也许有助于为我澄清这一点,或者展示一种更好的方式来解决这种情况。

【问题讨论】:

  • 您能更好地解释您要解决的问题吗?您会发现这不可能直接实现,所以我不知道该去哪里回答。
  • 我正在做一些事情,使用一个东西来扩展另一个可能提供或不提供资产的相同东西,你可以在这里看到它是如何结束的:github.com/thrisp/fleet/blob/develop/asset.go 和这里@987654322 @

标签: struct interface go


【解决方案1】:

你能不能只在MyStruct 上定义一个方法AFunction 来分派到存储的AFunction 函数指针?如果你有很多这样的东西并不理想,但我认为它可以完成工作?

即像

func (s MyStruct) AFunction(str string) ([]byte, error) {
    return s.AFunction(str)
}

编辑:以上可能会导致编译器出错,因为s.AFunction 不明确,因此您可能必须给它们(方法和函数指针)不同的名称,但它应该给出正确的想法。

【讨论】:

  • 是的,这就是我需要做的事情
【解决方案2】:

您可以将其包装在另一个实现该接口的结构中:

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

package main

import "fmt"

type (
    MyStruct struct {
        AFunction func(string) ([]byte, error)
    }

    MyInterface interface {
        AFunction(string) ([]byte, error)
    }
)

func NeedThis(s string) ([]byte, error) {
    //relevant function stuff
    return nil, nil
}

type Proxy struct {
    *MyStruct
}

func (x *Proxy) AFunction(s string) ([]byte, error) {
    return x.MyStruct.AFunction(s)
}

func main() {

    m := &MyStruct{AFunction: NeedThis}
    p := &Proxy{m}
    _, ok := MyInterface(p).(MyInterface)
    fmt.Println(ok)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2020-03-05
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多