go - 通过 switch 语句分配类型/创建结构

标签 go

我在弄清楚如何在 switch 语句中创建结构或在 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 函数,将特定类型的结构分配给 result 变量。

如果我可以提供更多信息,请告诉我。

最佳答案

由于您正在调用 .Print,因此您需要使用具有该方法的接口(interface)。我想你正在寻找类似的东西

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)
}

https://play.golang.org/p/W9r6UfeQSCz

关于go - 通过 switch 语句分配类型/创建结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50053711/

相关文章:

go - 类型断言失败,从 golang 中的 interface{} 正确转换

sql - 如何将数组设置为SQL查询的参数

go - FieldA.Eq 未定义(类型 cqlc.BooleanColumn 没有字段或方法 Eq)

go - 如何在 Go 中获得 5000 的阶乘

javascript - 将代码从 javascript 移植到 go 的问题

go - 错误类型 go lang

github - CircleCI & Golang - 无法导入 AWS SDK

go - 将 WireGuard 嵌入到 Windows 上的 Go 应用程序中

eclipse - 如何在 GoClipse 中交叉引用?

arrays - 数组精简或类似