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 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件