On Sat, Apr 02, 2022 at 12:41:00AM +0200, Victor Toso wrote:
> This patch handles QAPI union types and generates the equivalent data
> structures and methods in Go to handle it.
> 
> At the moment of this writing, it generates 67 structures.
> 
> The QAPI union type can be summarized by its common members that are
> defined in a @base struct and a @value. The @value type can vary and
> depends on @base's field that we call @discriminator. The
> @discriminator is always a Enum type.
> 
> Golang does not have Unions. The generation of QAPI union type in Go
> with this patch, follows similar approach to what is done for QAPI
> struct types and QAPI alternate types.

The common way to approach unions in Go is to just use a struct
where each union case is an optional field, and declare that only
one field must ever be set. ie

  type SocketAddressLegacy struct {
        // Value based on @type, possible types:
        Inet *InetSocketAddressWrapper
        Unix *UnixSocketAddressWrapper
        VSock *VsockSocketAddressWrapper
        FD *StringWrapper
  }

When deserializing from JSON we populate exactly one of the
optional fields.

When serializing to JSON process the first field that is
non-nil.

Note, you don't actually need to include the discriminator
as a field at all, since it is implicitly determined by
whichever case is non-nil.  Introducing the discriminator
as a field just provides the possibility for the programmer
to make inconsistent settings, for no gain.


With regards,
Daniel
-- 
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|


Reply via email to