Best practice for unions in Go

前端 未结 4 1538
一个人的身影
一个人的身影 2021-01-17 11:11

Go has no unions. But unions are necessary in many places. XML makes excessive use of unions or choice types. I tried to find out, which is the preferred way to work around

4条回答
  •  既然无缘
    2021-01-17 11:32

    I am not sure to understand your issue. The 'easy' way to do it would be like the encoding/xml package with interface{}. If you do not want to use interfaces, then you can do something like you did. However, as you stated, Go is a typed language and therefore should be use for typed needs. If you have a structured XML, Go can be a good fit, but you need to write your schema. If you want a variadic schema (one given field can have multiple types), then you might be better off with an non-typed language.

    Very useful tool for json that could easily rewritten for xml: http://mholt.github.io/json-to-go/

    You give a json input and it gives you the exact Go struct. You can have multiple types, but you need to know what field has what type. If you don't, you need to use the reflection and indeed you loose a lot of the interest of Go.

提交回复
热议问题