我想使用 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())
}
关于types - golang 在 switch 中动态创建接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766400/