qemu-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [RFC PATCH v1 4/8] qapi: golang: Generate qapi's union types in Go


From: Daniel P . Berrangé
Subject: Re: [RFC PATCH v1 4/8] qapi: golang: Generate qapi's union types in Go
Date: Tue, 10 May 2022 11:26:56 +0100
User-agent: Mutt/2.1.5 (2021-12-30)

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

[Prev in Thread] Current Thread [Next in Thread]