types - golang 在 switch 中动态创建接收器

标签 types go interface dynamically-generated receiver

我想使用 Process 接口(interface)中实现的 Read 和 Write 方法从不同来源读取、提取和保存数据 该代码在第一个 example 中正常工作:

type Process interface {
    Read()
    write() string
}

type Nc struct {
    data string
}

type Ctd Nc
type Btl Nc

func (nc *Ctd) Read() {
    nc.data = "CTD"
}
func (nc *Ctd) Write() string {
    return nc.data
}
func (nc *Btl) Read() {
    nc.data = "BTL"
}
func (nc *Btl) Write() string {
    return nc.data
}

func main() {
    var ctd = new(Ctd)
    var btl= new(Btl)
    ctd.Read()
    btl.Read()
    fmt.Println(ctd.Write())
    fmt.Println(btl.Write())
}

现在,我想从文件中动态读取数据,方法 get_config 应该返回我想在 switch 中处理的常量类型 block 为:

func main() {
    // bitMask = get_config()
    bitMask := 1
    // or bitmask := 2
    var nc = new(Nc)
    switch bitMask {
    case 1:
        nc = Ctd(nc)
    case 2:
        nc = Btl(nc)
    }
    nc.Read()
    fmt.Println(nc.Write())
}

我不知道如何在 switch block 之外声明具有正确类型的 nc

谢谢,

最佳答案

在接口(interface)中,write 方法是小写的,所以它是私有(private)的。并且结构 Ctd 和 Btl 没有实现这个接口(interface),因为它们有大写的 Write 方法。

所以:

type Process interface {
    Read()
    Write() string
}

....

func main() {
  bitMask := 2
  // or bitMask := 2
  var nc Process
  switch bitMask {
  case 1:
    nc = &Ctd{}
  case 2:
    nc = &Btl{}
  }
  nc.Read()
  fmt.Println(nc.Write())
}

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

关于types - golang 在 switch 中动态创建接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766400/

相关文章:

C# 扩展接口(interface)实现作为参数来委托(delegate)采用基接口(interface)

types - 什么时候更喜欢F#中的无类型引用而不是有类型的引用?

C++ 问题类型

c++ - 具有默认类型和值的模板参数

objective-c - 在 Objective-C 中注释 NSArray<NSNumber *> * 以便桥接到 Array<Int>

go - 最新稳定 Go 版本的 URL

go - Go 中如何将字节数组转换为字符串数组?

java - 实现一个接口(interface),该接口(interface)有一个返回接口(interface)的方法,但收到未实现的错误

c# - 说明该类必须具有 ICollection<T> 属性的接口(interface)

linux - 在覆盖 go 的默认信号处理程序时如何避免竞争?