我在弄清楚如何在switch语句中创建struct或在switch语句中为其分配类型时遇到了一些困难。下面是一些不起作用的代码,说明我试图做什么:
var result
switch structPickingString {
case "struct1":
result = new(struct1)
case "struct2":
result = new(struct2)
}
//unmarshall some json into the appropriate struct type
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Println(err)
}
//print out that json with a function specific to that type of struct
result.Print()我认为涉及一个空的interface{}的东西可能与解决这个问题有关,但不幸的是,我对golang仍然有点无知,我不知道如何使它工作。
下面链接到代码的一个稍微修改的版本,以获得更多的上下文:https://play.golang.org/p/Rb1oaMuvmU2
问题不是定义打印函数,而是根据结构实现的单个Print函数将特定类型的结构分配给Print变量。
如果我能提供更多的信息,请告诉我。
发布于 2018-04-27 00:53:31
由于您正在调用.Print,所以需要使用具有该方法的接口。我想你是在找
type Printer interface {
Print()
}
func (s *struct1) Print() {
// ...
}
func (s *struct2) Print() {
// ...
}
var result Printer
switch structPickingString {
case "struct1":
result = new(struct1)
case "struct2":
result = new(struct2)
}发布于 2018-04-27 01:06:36
您需要将“通用接口”与结构匹配。见此:
//my struct1
type MyStruct1 struct {
ID int
}
//my struct2
type MyStruct2 struct {
ID int
}
//my interface
type MyStructGenerical interface {
Print()
}
//method (match with MyStructGenerical)
func (m1 MyStruct1) Print() {
println(m1.ID)
}
//method (match with MyStructGenerical)
func (m2 MyStruct2) Print() {
println(m2.ID)
}通过这种方式,您可以在结构和通用接口之间进行断言。见此:
//here result is an generical interface
var result MyStructGenerical = nil
//checkin
switch structPickingString {
case "struct1":
tmp := new(MyStruct1)
result = tmp
case "struct2":
tmp := new(MyStruct2)
result = tmp
}结果是:
//unmarshall some json into the appropriate struct type
if err := json.NewDecoder(body()).Decode(&result); err != nil {
log.Println(err)
}
//print out that json with a function specific to that type of struct
tmp := result.(*MyStruct1)
tmp.Print()
// or
result.Print()发布于 2018-04-27 00:58:48
我想你想用一个像
type ResultIface interface {
Print()
}那你就可以
var result ResultIface
switch structPickingString {
case "struct1":
result = new(struct1)
case "struct2":
result = new(struct2)
}只要您的struct1和struct2有一个打印函数来实现ResultIface,它就会打印出来。
https://stackoverflow.com/questions/50053711
复制相似问题