Best practice for unions in Go

前端 未结 4 1518
一个人的身影
一个人的身影 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

    TL;DR You don't need a union, interface{} solves this better.

    Unions in C are used to access special memory/hardware. They also subvert the type system. Go does not have the language primitives access special memory/hardware, it also shunned volatile and bit-fields for the same reason.

    In C/C++ unions can also be used for really low level optimization / bit packing. The trade off: sacrifice the type system and increase complexity in favor of saving some bits. This of course comes with all the warnings about optimizations.

    Imagine Go had a native union type. How would the code be better? Rewrite the code with this:

    // pretend this struct was a union
    type MiscUnion struct {
      c *Comment
      pi *ProcessingInstruction
      ws *WhiteSpace
    }
    

    Even with a builtin union accessing the members of MiscUnion requires a runtime check of some kind. So using an interface is no worse off. Arguably the interface is superior as the runtime type checking is builtin (impossible to get wrong) and has really nice syntax for dealing with it.

    One advantage of a union type is static type check to make sure only proper concrete types where put in a Misc. The Go way of solving this is "New..." functions, e.g. MiscComment, MiscProcessingInstruction, MiscWhiteSpace.

    Here is a cleaned up example using interface{} and New* functions: http://play.golang.org/p/d5bC8mZAB_

提交回复
热议问题