doutiaoku4495 2019-05-03 09:11
浏览 28
已采纳

转到:动态结构组成

I'm looking to understand which is the most suitable approach to solve the following problem.

I have a struct that represents the data to be serialised as part of a JSON response. A property on this struct config can be one of three possible structs, however, the only way I know to represent this is using the type interface{} and have the caller type assert the property.

type Response struct {
    Field1 string      `json:"field1"`
    Field2 int         `json:"field2"`
    Config interface{} `json:"config"`
}

type ConfigOne struct {
    SomeField string
}

type ConfigTwo struct {
    SomeField int
}

type ConfigThree struct {
    SomeField bool
}

Then I can have New style functions to create the right instance for me:

func NewConfigTwo() *Response {
    return &Response{
        Field1: "hello",
        Field2: 1,
        Config: ConfigTwo{
            SomeField: 22,
        },
    }
}

Is there a better way to represent a field with a enum like type of structs? Or is this as good as I can make it?

I'd appreciate any clarity or suggestions on how best to achieve this.

  • 写回答

1条回答 默认 最新

  • doormen2014 2019-05-03 12:50
    关注

    Essentially, you're trying to implement an algebraic data type here. To expand on @mkopriva's comment, take a look at this post: Go and algebraic data types. Essentially you'll specify a non-empty interface such that all possible types implement a method and others don't satisfy the interface "by chance" (whereas every type implements interface{}) and then use type switches.

    Something like (untested):

    type Response struct {
        Field1 string      `json:"field1"`
        Field2 int         `json:"field2"`
        Config Configable  `json:"config"`
    }
    
    type Configable interface {
        isConfig()
    }
    
    type ConfigOne struct {
        SomeField string
    }
    
    func (ConfigOne) isConfig() {}
    
    // ... and so on for other Config* types
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入