Best practice for unions in Go

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

    As it seems that you're asking because you want type safety, I would firstly argue that your initial solution is already unsafe as you have

    func (m Misc) Comment () *Comment {
        return m.value.(*Comment)
    }
    

    which will panic if you haven't checked IsComment before. Therefore this solution has no benefits over a type switch as proposed by Volker.

    Since you want to group your code you could write a function that determines what a Misc element is:

    func IsMisc(v {}interface) bool {
        switch v.(type) {
            case Comment: return true
            // ...
        }
    }
    

    That, however, would bring you no compiler type checking either.

    If you want to be able to identify something as Misc by the compiler then you should consider creating an interface that marks something as Misc:

    type Misc interface {
        ImplementsMisc()
    }
    
    type Comment Chars
    func (c Comment) ImplementsMisc() {}
    
    type ProcessingInstruction
    func (p ProcessingInstruction) ImplementsMisc() {}
    

    This way you could write functions that are only handling misc. objects and get decide later what you really want to handle (Comments, instructions, ...) in these functions.

    If you want to mimic unions then the way you wrote it is the way to go as far as I know.

提交回复
热议问题