jeudi 9 mai 2019

Idiomatic way to represent one of/union in Go

I'm looking to implement a struct that can either be a Foo or a Bar.

So right now I have:

type Foo struct{}
type Bar struct{} 

// This is the end version consumed by my package
type Baz struct {
  Foo Foo `json:"foo,omitempty"`
  Bar Bar `json:"bar,omitempty"`
  // ... there are different members here
}

Then in my internal functions I need to check whether the Baz contains a Foo or Bar and handle them differently.

Is there an idiomatic way to handle this? Right now I am checking if the members of Foo are the default values but this feels hacky.

I've considered making the members pointers so they are nullable and I can then check them against nil.

Am I missing something here?

Aucun commentaire:

Enregistrer un commentaire