Skip to content
Arne K. (TRC-Loop) edited this page Nov 14, 2026 · 2 revisions

Enums

Rust enums are sum types: a value is exactly one of several variants, and each variant can carry data.

enum Shape {
    Circle { radius: f64 },        // struct variant
    Rect(f64, f64),                // tuple variant
    Empty,                         // unit variant
    Label(String),                 // newtype variant
    Polygon { points: Vec<(i32, i32)> },
}

In RON these look like Circle(radius: 1.5), Rect(2.0, 3.0), Empty and Label("hi"). Go has no sum types, so rustyon models an enum as an interface and each variant as a Go type that implements it. A Registry maps between variant names and Go types.

Defining and registering an enum

type Shape interface{ isShape() }

type Circle struct{ Radius float64 } // struct variant
type Rect struct {                   // tuple variant
    _    struct{} `ron:",tuple"`
    W, H float64
}
type Empty struct{} // unit variant
type Label string   // newtype variant

// Polygon implements Shape with a pointer receiver.
type Polygon struct{ Points []Pt }

// Pt is the tuple (i32, i32).
type Pt struct {
    _    struct{} `ron:",tuple"`
    X, Y int
}

func (Circle) isShape()   {}
func (Rect) isShape()     {}
func (Empty) isShape()    {}
func (Label) isShape()    {}
func (*Polygon) isShape() {}

func init() {
    rustyon.RegisterEnum[Shape](
        rustyon.Variant[Circle]("Circle"),
        rustyon.Variant[Rect]("Rect"),
        rustyon.Variant[Empty]("Empty"),
        rustyon.Variant[Label]("Label"),
        rustyon.Variant[*Polygon]("Polygon"),
    )
}

The API:

Function Purpose
Variant[T any](name string) VariantSpec Declares that Go type T is the variant called name.
RegisterEnum[I any](variants ...VariantSpec) Registers interface I as an enum in DefaultRegistry.
RegisterEnumIn[I any](r *Registry, variants ...VariantSpec) Same, into a specific registry.
RegisterEnumWith[I any](opts EnumOptions, variants ...VariantSpec) Like RegisterEnum with another representation: internally tagged, adjacently tagged or untagged.
RegisterEnumWithIn[I any](r *Registry, opts EnumOptions, variants ...VariantSpec) Same, into a specific registry.
RegisterUnitEnum[T comparable](names map[T]string) Registers a type whose values are data-less variants (Go constants).
RegisterUnitEnumIn[T comparable](r *Registry, names map[T]string) Same, into a specific registry.
NewRegistry() *Registry Creates an empty registry.
DefaultRegistry The registry used by Marshal, Unmarshal and by encoders and decoders without their own.

Register once, typically in an init function. Registering the same interface again adds variants to it. A Registry is safe for concurrent use.

Variant kinds

How a variant is written depends on its Go type:

Go variant type Rust variant RON
struct with no fields unit variant Empty
struct with the tuple option tuple variant Rect(2.0, 3.0)
struct with named fields struct variant Circle(radius: 1.5)
any other type (string, number, slice, map, ...) newtype variant Label("hi")

Variant names always come from the registry, not from the Go type name or a _ tag, and are written whether or not struct names are enabled.

shapes := []Shape{
    Circle{Radius: 1.5},
    Rect{W: 2, H: 3},
    Empty{},
    Label("hi"),
    &Polygon{Points: []Pt{{X: 0, Y: 0}, {X: 1, Y: 1}}},
    nil,
}
out, _ := rustyon.MarshalIndent(shapes, "", "    ")
fmt.Println(string(out))

var back []Shape
rustyon.Unmarshal(out, &back)
for _, s := range back {
    fmt.Printf("%T\n", s)
}

Output:

[
    Circle(
        radius: 1.5,
    ),
    Rect(2.0, 3.0),
    Empty,
    Label("hi"),
    Polygon(
        points: [
            (0, 0),
            (1, 1),
        ],
    ),
    None,
]
main.Circle
main.Rect
main.Empty
main.Label
*main.Polygon
<nil>

Nil interfaces are None

A nil interface encodes as None, and None decodes into a nil interface. This makes an enum interface field behave like Option<Shape>.

Pointer receiver variants

If the interface is implemented by a pointer receiver, register the pointer type: Variant[*Polygon]("Polygon"). Registering Variant[Polygon] panics because Polygon itself does not implement Shape. Decoding then stores a *Polygon in the interface. A nil *Polygon stored in the interface encodes as None.

Accepted input forms

When decoding into a registered interface, the decoder takes the variant name from an identifier, a named tuple, a named struct or a string, then decodes the payload into the variant's Go type:

for _, src := range []string{
    `Circle(radius: 1.0)`,
    `Circle((radius: 1.0))`,
    `Rect(1.0, 2.0)`,
    `Empty`,
    `Empty()`,
    `"Empty"`,
    `Label("x")`,
    `Some(Empty)`,
    `None`,
} {
    var s Shape
    rustyon.Unmarshal([]byte(src), &s)
    fmt.Printf("%-22s %#v\n", src, s)
}
Circle(radius: 1.0)    main.Circle{Radius:1}
Circle((radius: 1.0))  main.Circle{Radius:1}
Rect(1.0, 2.0)         main.Rect{_:struct {}{}, W:1, H:2}
Empty                  main.Empty{}
Empty()                main.Empty{}
"Empty"                main.Empty{}
Label("x")             "x"
Some(Empty)            main.Empty{}
None                   <nil>
  • Circle((radius: 1.0)) is the explicit newtype form; Circle(radius: 1.0) is what the unwrap_variant_newtypes extension allows. Both are always accepted.
  • A bare variant name decodes into a struct variant with all fields zero, so Circle alone gives Circle{Radius: 0}.
  • Some(v) around a variant is unwrapped.

Decoding into the concrete type

A registered variant type also works as a direct target, and encodes with its variant name even outside the interface:

var c Circle
rustyon.Unmarshal([]byte(`Circle(radius: 4.0)`), &c)
out, _ := rustyon.Marshal(c)
fmt.Println(c.Radius, string(out)) // 4 Circle(radius:4.0)

Other representations

RON's native enum syntax (Circle(radius: 1.5)) is serde's external representation. Rust types that use #[serde(tag = "...")], #[serde(tag = "...", content = "...")] or #[serde(untagged)] look different on disk. RegisterEnumWith takes an EnumOptions that selects the representation, using serde's names. The output matches what ron-rs reads and writes; the library's tests check this against a ron-rs oracle.

type EnumOptions struct {
    Tag      string
    Content  string
    Untagged bool
}
Rust attribute EnumOptions Circle { radius: 1.5 } is written as
none (default) zero value, or use RegisterEnum Circle(radius:1.5)
#[serde(tag = "type")] {Tag: "type"} (type:"Circle",radius:1.5)
#[serde(tag = "t", content = "c")] {Tag: "t", Content: "c"} (t:Circle,c:(radius:1.5))
#[serde(untagged)] {Untagged: true} (radius:1.5)

The examples use these types. Circle, Rect, Empty and Label are the ones from the top of the page; Poly is new:

type Poly struct {
    Sides int
    Name  *string
}
func (Poly) isShape() {}

name := "tri"

Register each representation into its own registry (one interface has one representation) and pass the registry with EncodeOptions and DecodeOptions:

Internally tagged

internal := rustyon.NewRegistry()
rustyon.RegisterEnumWithIn[Shape](internal, rustyon.EnumOptions{Tag: "type"},
    rustyon.Variant[Circle]("Circle"),
    rustyon.Variant[Poly]("Poly"),
    rustyon.Variant[Empty]("Empty"),
)

shapes := []Shape{Circle{1.5}, Poly{3, &name}, Empty{}}
out, _ := rustyon.MarshalWith(shapes, rustyon.EncodeOptions{Registry: internal})
fmt.Println(string(out))
// [(type:"Circle",radius:1.5),(type:"Poly",sides:3,name:Some("tri")),(type:"Empty")]

The variant is a struct with an extra field that holds the variant name as a string. A unit variant is just (type:"Empty"). When decoding, the tag may appear anywhere and may be a string or an identifier:

var back []Shape
err := rustyon.UnmarshalWith([]byte(`[(radius: 2.0, type: Circle), (type: "Empty")]`), &back,
    rustyon.DecodeOptions{Registry: internal})
fmt.Printf("%#v %v\n", back, err)
// []main.Shape{main.Circle{Radius:2}, main.Empty{}} <nil>

Rules and limits, as in serde:

  • Variants must be structs (including unit structs), or newtypes around a struct or a map with string keys. Tuple variants and newtypes around other types cannot be encoded:

    rustyon: unsupported value: variant Rect of an internally tagged enum cannot be a tuple
    rustyon: unsupported value: variant Label of an internally tagged enum must contain a struct or a map
    
  • A struct variant must not have a field with the same name as the tag.

  • Decoding errors say what is wrong with the tag:

    rustyon: cannot unmarshal struct into Go value of type main.Shape: missing the "type" field
    rustyon: cannot unmarshal struct into Go value of type main.Shape: unknown variant "Nope"
    rustyon: cannot unmarshal struct into Go value of type main.Shape: the "type" field must be a string
    
  • A concrete variant type decodes with or without the tag, but a wrong tag is rejected.

  • With DisallowUnknownFields, the tag field itself is not unknown.

Adjacently tagged

adj := rustyon.NewRegistry()
rustyon.RegisterEnumWithIn[Shape](adj, rustyon.EnumOptions{Tag: "t", Content: "c"},
    rustyon.Variant[Circle]("Circle"),
    rustyon.Variant[Rect]("Rect"),
    rustyon.Variant[Label]("Label"),
    rustyon.Variant[Empty]("Empty"),
)

out, _ := rustyon.MarshalWith([]Shape{Circle{1}, Rect{W: 2, H: 3}, Label("hi"), Empty{}},
    rustyon.EncodeOptions{Registry: adj})
fmt.Println(string(out))
// [(t:Circle,c:(radius:1.0)),(t:Rect,c:(2.0,3.0)),(t:Label,c:"hi"),(t:Empty)]

Any variant kind works here, because the content has its own field. The tag is written as an identifier, as serde does, and a unit variant leaves out the content. Decoding accepts the tag as an identifier or a string, the fields in either order, and c: () for a unit variant:

var ab []Shape
err := rustyon.UnmarshalWith(
    []byte(`[(c: "y", t: "Label"), (t: "Empty", c: ()), (t: Rect, c: (3.0, 4.0))]`),
    &ab, rustyon.DecodeOptions{Registry: adj})
fmt.Printf("%#v %v\n", ab, err)
// []main.Shape{"y", main.Empty{}, main.Rect{_:struct {}{}, W:3, H:4}} <nil>

Untagged

unt := rustyon.NewRegistry()
rustyon.RegisterEnumWithIn[Shape](unt, rustyon.EnumOptions{Untagged: true},
    rustyon.Variant[Circle]("Circle"),
    rustyon.Variant[Poly]("Poly"),
    rustyon.Variant[Rect]("Rect"),
    rustyon.Variant[Label]("Label"),
    rustyon.Variant[Empty]("Empty"),
)

out, _ := rustyon.MarshalWith(
    []Shape{Circle{1}, Poly{2, &name}, Rect{W: 3, H: 4}, Label("l"), Empty{}},
    rustyon.EncodeOptions{Registry: unt})
fmt.Println(string(out))
// [(radius:1.0),(sides:2,name:Some("tri")),(3.0,4.0),"l",()]

The variant is written as its content alone, with no variant name. Decoding tries the variants in registration order and takes the first that fits:

  • a struct variant fits when the input has all of its fields. Pointer, interface, omitempty and omitzero fields may be missing. Fields the variant does not know are ignored, unless DisallowUnknownFields is set;
  • a tuple variant fits a tuple of the right length;
  • a unit variant fits () only;
  • a newtype variant fits when its inner type decodes the value.
var ub []Shape
err := rustyon.UnmarshalWith(
    []byte(`[(sides: 1), (radius: 2.0, junk: 1), (3.0, 4.0), "s", ()]`),
    &ub, rustyon.DecodeOptions{Registry: unt})
fmt.Printf("%#v %v\n", ub, err)
// []main.Shape{main.Poly{Sides:1, Name:(*string)(nil)}, main.Circle{Radius:2}, main.Rect{_:struct {}{}, W:3, H:4}, "s", main.Empty{}} <nil>

(sides: 1) fits Poly (the Name pointer may be missing), (radius: 2.0, junk: 1) fits Circle, "s" fits Label. If nothing fits, decoding fails:

rustyon: cannot unmarshal struct into Go value of type main.Shape: no variant matches

Because the first match wins, order matters: put variants with more fields first when one variant's fields are a subset of another's. A failed attempt leaves nothing behind in the result. Decoding an untagged enum tries each variant, so it costs more than the other representations, see Performance.

Registration rules

RegisterEnumWith panics, like RegisterEnum, for invalid options:

Mistake Panic message
Content without Tag rustyon: RegisterEnum main.Shape: Content requires Tag
Untagged with Tag or Content rustyon: RegisterEnum main.Shape: Untagged cannot be combined with Tag or Content
Tag equal to Content rustyon: RegisterEnum main.Shape: Tag and Content must differ
Tag or Content that is not a valid identifier rustyon: RegisterEnum main.Shape: Tag and Content must be valid identifiers
registering an interface again with another representation rustyon: RegisterEnum main.Shape: already registered with another representation

Registering the same interface again with the same options adds variants, as with RegisterEnum. RegisterEnumIn is RegisterEnumWithIn with the zero EnumOptions.

A type that is a variant of several enums with different representations or names is only treated as a variant when it is stored in one of their interfaces, not when it is encoded or decoded on its own (see A type in several enums).

The representation applies to the registry that you pass with EncodeOptions.Registry, DecodeOptions.Registry, Encoder.SetRegistry or Decoder.SetRegistry, so the same Go types can be written in different styles by using different registries.

Unit enums on Go constants

Enums whose variants carry no data are often plain constants in Go. RegisterUnitEnum maps each value to a variant name. Values encode as bare identifiers and decode from identifiers or strings. Any comparable type works: integer types, string types and so on.

type Difficulty int

const (
    Easy Difficulty = iota
    Normal
    Hard
)

func init() {
    rustyon.RegisterUnitEnum(map[Difficulty]string{
        Easy:   "Easy",
        Normal: "Normal",
        Hard:   "Hard",
    })
}

type Settings struct {
    Difficulty Difficulty
    PerLevel   map[Difficulty]int
}

var s Settings
rustyon.Unmarshal([]byte(`(difficulty: Hard, per_level: {Easy: 1, "Normal": 2})`), &s)
fmt.Println(s.Difficulty == Hard, s.PerLevel[Normal]) // true 2

out, _ := rustyon.Marshal(s)
fmt.Println(string(out)) // (difficulty:Hard,per_level:{Easy:1,Normal:2})

_, err := rustyon.Marshal(Difficulty(7))
fmt.Println(err)
// rustyon: unsupported value: value 7 of unit enum main.Difficulty has no registered name

Unit enums work as map keys, as shown. A slice of a unit enum based on uint8 is a list of identifiers, not a byte string. Calling RegisterUnitEnum again for the same type replaces the previous names.

Custom registries

RegisterEnumIn and RegisterUnitEnumIn register into a registry you create with NewRegistry. Pass it to an Encoder or Decoder with SetRegistry; see Getting Started. Marshal, Unmarshal, ToValue and FromValue always use DefaultRegistry.

A type in several enums

One Go type can be a variant of several enums, possibly under different names. The name used for encoding depends on the static type the value is stored in:

  • In a field or element whose type is a registered enum interface, that enum's name is used.
  • Otherwise (a concrete field, any, a top level value) the type must have a single name across all enums it belongs to. If its names differ, it is not treated as a variant and encodes as a plain struct.
type Pet interface{ isPet() }
type Animal interface{ isAnimal() }
type Dog struct{ Name string }

func (Dog) isPet()    {}
func (Dog) isAnimal() {}

reg := rustyon.NewRegistry()
rustyon.RegisterEnumIn[Pet](reg, rustyon.Variant[Dog]("Doggo"))
rustyon.RegisterEnumIn[Animal](reg, rustyon.Variant[Dog]("Dog"))

enc := rustyon.NewEncoder(os.Stdout)
enc.SetRegistry(reg)
enc.Encode(struct {
    P Pet
    A Animal
    X any
}{Dog{"a"}, Dog{"b"}, Dog{"c"}})
// (p:Doggo(name:"a"),a:Dog(name:"b"),x:(name:"c"))

Errors

Decoding problems are reported as *UnmarshalTypeError:

for _, src := range []string{`Triangle(1.0)`, `(radius: 1.0)`, `5`, `Circle(radius: "big")`} {
    var s Shape
    fmt.Println(rustyon.Unmarshal([]byte(src), &s))
}
var d Difficulty
fmt.Println(rustyon.Unmarshal([]byte(`Insane`), &d))
fmt.Println(rustyon.Unmarshal([]byte(`1`), &d))

var r fmt.Stringer
fmt.Println(rustyon.Unmarshal([]byte(`1`), &r))
rustyon: cannot unmarshal tuple Triangle into Go value of type main.Shape: unknown variant "Triangle"
rustyon: cannot unmarshal struct into Go value of type main.Shape: expected an enum variant
rustyon: cannot unmarshal integer into Go value of type main.Shape: expected an enum variant
rustyon: cannot unmarshal string into Go value of type float64 at (Circle).radius
rustyon: cannot unmarshal identifier Insane into Go value of type main.Difficulty: unknown variant "Insane"
rustyon: cannot unmarshal integer into Go value of type main.Difficulty: expected a unit variant
rustyon: cannot unmarshal integer into Go value of type fmt.Stringer: interface type is not a registered enum

Inside a variant, the error path contains the variant name in parentheses, for example shapes[0].(Circle).radius.

Encoding a unit enum value without a registered name returns an *UnsupportedValueError, as shown above.

Registration mistakes are programming errors, so the Register functions panic:

Mistake Panic message
I is not an interface rustyon: RegisterEnum: main.Circle is not an interface type
variant does not implement I (including a value type when only the pointer implements it) rustyon: RegisterEnum main.Shape: variant type main.Polygon does not implement it
invalid variant name (empty, or characters not allowed even in a raw identifier) rustyon: RegisterEnum main.Shape: invalid variant name "bad name"
two types with the same name rustyon: RegisterEnum main.Shape: duplicate variant name "X"
one type with two names rustyon: RegisterEnum main.Shape: type main.Circle registered twice
a variant that is itself an interface type ... variant ... is an interface type
a zero VariantSpec{} ... zero VariantSpec
RegisterUnitEnum with an invalid or duplicate name rustyon: RegisterUnitEnum main.Difficulty: duplicate variant name "A"

Variant names may be any valid raw identifier, so names such as true or my-variant work and are written as r#true or r#my-variant.

Clone this wiki locally