douliao5467 2018-04-27 00:43
浏览 44
已采纳

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

I'm having a bit of trouble figuring out how to either create a struct in a switch statement or assign a type to it in a switch statement. Here's some non-working code illustrating what I'm trying to do:

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

I think something involving an empty interface{} might be related to solving this issue but unfortunately I'm still a bit ignorant with golang and I'm not seeing how to make it work.

Here's a link to a slightly modified version of the code for more context: https://play.golang.org/p/Rb1oaMuvmU2

The issue is not defining the print function, it's assigning a specific type of struct to the result variable based on using the individual Print function that the struct implements.

Let me know if there's any more info I could provide.

  • 写回答

3条回答 默认 最新

  • douhanshu5517 2018-04-27 00:53
    关注

    Since you are calling .Print, you need to use an interface which has that method. I think you are looking for something like

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊