Skip to content

Struct Tags

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

Struct Tags

Struct fields are controlled with the ron struct tag, in the same style as encoding/json:

Field Type `ron:"name,option,option"`

The name part is optional, so ron:",omitempty" keeps the default name.

Default naming: snake_case

Without a tag, the RON field name is the snake_case form of the Go field name. That is the convention Rust uses, so Go structs match Rust structs without any tags.

Go field RON field
Name name
MaxHP max_hp
HTTPServer http_server
UserID user_id
ABTest ab_test
Vec2D vec2_d
Field2 field2
ÜberCool über_cool

The rule: an underscore goes before an upper case letter that follows a lower case letter or a digit, and before the last upper case letter of an acronym when a lower case letter follows it. All letters are then lower cased.

type Stats struct {
    Name       string
    MaxHP      int
    HTTPServer string
    UserID     int
    Vec2D      int
    ABTest     bool
}
out, _ := rustyon.MarshalIndent(Stats{}, "", "    ")
fmt.Println(string(out))
(
    name: "",
    max_hp: 0,
    http_server: "",
    user_id: 0,
    vec2_d: 0,
    ab_test: false,
)

Unexported fields are ignored.

Field naming strategies

snake_case is the default, but not every RON file follows it. A NamingStrategy picks another convention for Go field names that have no explicit ron:"name" tag.

Strategy serde name MaxHP HTTPServer
SnakeCase (default) snake_case max_hp http_server
CamelCase camelCase maxHp httpServer
PascalCase PascalCase MaxHp HttpServer
ScreamingSnakeCase SCREAMING_SNAKE_CASE MAX_HP HTTP_SERVER
KebabCase kebab-case r#max-hp r#http-server
ScreamingKebabCase SCREAMING-KEBAB-CASE r#MAX-HP r#HTTP-SERVER
LowerCase lowercase maxhp httpserver
UpperCase UPPERCASE MAXHP HTTPSERVER
Identity identity MaxHP HTTPServer

The kebab strategies produce names that are not plain RON identifiers, so they are written as raw identifiers (r#max-hp). They round trip, but a file written by hand for them needs the r# prefix. Words are split the same way as for snake_case, so HTTPServer is the words http and server.

NamingStrategy.String() returns the serde name and NamingStrategy.Name(goName) converts a single name:

s := rustyon.CamelCase
fmt.Println(s, s.Name("MaxHP")) // camelCase maxHp

Setting the strategy

For everything one call handles:

type Stats struct {
    MaxHP      int
    HTTPServer string
    UserID     int
}

out, _ := rustyon.MarshalWith(Stats{1, "h", 2}, rustyon.EncodeOptions{FieldNaming: rustyon.CamelCase})
fmt.Println(string(out))
// (maxHp:1,httpServer:"h",userId:2)

var s Stats
err := rustyon.UnmarshalWith(out, &s, rustyon.DecodeOptions{FieldNaming: rustyon.CamelCase})
fmt.Printf("%+v %v\n", s, err)
// {MaxHP:1 HTTPServer:h UserID:2} <nil>

For a stream, use Encoder.SetFieldNaming and Decoder.SetFieldNaming. UnmarshalAs[T] takes DecodeOptions as an optional second argument, see Type Mapping.

var buf bytes.Buffer
enc := rustyon.NewEncoder(&buf)
enc.SetFieldNaming(rustyon.ScreamingSnakeCase)
enc.Encode(Stats{1, "h", 2})
fmt.Print(buf.String())
// (MAX_HP:1,HTTP_SERVER:"h",USER_ID:2)

dec := rustyon.NewDecoder(&buf)
dec.SetFieldNaming(rustyon.ScreamingSnakeCase)
var back Stats
err := dec.Decode(&back)
fmt.Printf("%+v %v\n", back, err)
// {MaxHP:1 HTTPServer:h UserID:2} <nil>

MarshalWith also takes StructNames, ImplicitSome, UnwrapNewtypes, a Registry and a Pretty layout. UnmarshalWith takes DisallowUnknownFields and a Registry. The zero value of both option structs behaves exactly like Marshal and Unmarshal.

Per struct: rename_all

Like serde's #[serde(rename_all = "...")], a struct can choose its own naming with the rename_all= option on the blank _ struct{} field. It takes the serde names from the table above:

type Window struct {
    _     struct{} `ron:",rename_all=PascalCase"`
    Title string
    Size  [2]int
}

type Config struct {
    WindowTitle string
    MaxFPS      int
    Explicit    int `ron:"Keep_This"`
    Win         Window
}

out, _ := rustyon.MarshalWith(Config{"main", 60, 1, Window{Title: "t", Size: [2]int{800, 600}}},
    rustyon.EncodeOptions{FieldNaming: rustyon.CamelCase, Pretty: &rustyon.PrettyConfig{CompactArrays: true}})
fmt.Println(string(out))
(
    windowTitle: "main",
    maxFps: 60,
    Keep_This: 1,
    win: (
        Title: "t",
        Size: [800, 600],
    ),
)

The rules:

  • An explicit ron:"name" tag always wins over any strategy (Keep_This).
  • rename_all on a struct beats the encoder or decoder default for that struct's own fields. It is not inherited by nested structs: Win is named by the default (win), while its fields use PascalCase.
  • An embedded struct that has its own rename_all keeps it for its fields, so an embedded _ struct{} ron:",rename_all=SCREAMING_SNAKE_CASE" struct with a field InnerA gives INNER_A next to the outer struct's outerB.
  • It also applies to the fields of enum variants: a variant struct with rename_all=camelCase and a field BigRad is written Circle(bigRad:2.0).
  • An unknown rename_all value is ignored, so the default strategy stays in effect.
  • When decoding, the lookup is exact first, then case-insensitive, with the chosen names. With LowerCase, the input MAXHP matches the field MaxHP.
  • The default naming does not see other styles: Unmarshal of (windowTitle: "x") leaves WindowTitle empty and does not fail.

Tag options

Tag Effect
ron:"name" Use name as the RON field name.
ron:",omitempty" Skip the field when encoding if it is empty: false, 0, "", a nil pointer or interface, or a slice, map, array or string of length 0. Structs are never empty.
ron:",omitzero" Skip the field when encoding if it is the zero value. If the type (or its pointer) has an IsZero() bool method, that method decides.
ron:"-" Never encode or decode the field.
ron:",flatten" Write the fields of a struct field inline in the parent, or collect unknown fields in a map[string]T. See Flatten.
ron:",rename_all=camelCase" On the blank _ field only: name the struct's fields with another strategy.

omitempty and omitzero only affect encoding; they can be combined.

// Range implements IsZero, which omitzero uses.
type Range struct{ Min, Max int }

func (r Range) IsZero() bool { return r.Min == 0 && r.Max == 0 }

type Item struct {
    ID       int      `ron:"id"`
    Kind     string   `ron:"type"`
    Note     string   `ron:",omitempty"`
    Tags     []string `ron:"labels,omitempty"`
    Parent   *int     `ron:",omitempty"`
    Range    Range    `ron:",omitzero"`
    Cache    []byte   `ron:"-"`
    internal int
}

out, _ := rustyon.Marshal(Item{ID: 1, Kind: "sword", Cache: []byte{1}, internal: 2})
fmt.Println(string(out))
// (id:1,type:"sword")

out, _ = rustyon.Marshal(Item{ID: 2, Note: "n", Tags: []string{"a"}, Range: Range{1, 5}})
fmt.Println(string(out))
// (id:2,type:"",note:"n",labels:["a"],range:(min:1,max:5))

Names that need raw identifiers

A tag name may be a Rust keyword or contain -, . or +. Such names are written as raw identifiers when needed:

out, _ := rustyon.Marshal(struct {
    A int `ron:"true"`
    B int `ron:"key-name"`
}{1, 2})
fmt.Println(string(out)) // (r#true:1,r#key-name:2)

A name like type is a plain identifier in RON and needs no prefix. A name that cannot be written even as a raw identifier (for example one with a space) makes Marshal fail with an *UnsupportedValueError.

The _ field: struct name and tuple structs

A blank field named _ of type struct{} carries options for the whole struct:

_ struct{} `ron:"Name,tuple"`
  • Name sets the RON struct name. Without it the Go type name is used. Struct names are written only when Encoder.SetStructNames(true) is on and are never checked when decoding. Enum variant names do not come from this tag but from the registry.
  • tuple encodes the struct as a tuple struct, (a, b) instead of (a: a, b: b), with the exported fields in order.

The field takes no space (struct{} has size 0) and is ignored for encoding otherwise.

Tuple structs

type Point struct {
    _    struct{} `ron:",tuple"`
    X, Y float64
}

Point{X: 1, Y: 2.5} encodes as (1.0, 2.5), or Point(1.0, 2.5) with struct names on. When decoding, a tuple struct accepts a tuple of exactly the right length. Any struct, tuple or not, can also decode from a tuple by position, from a struct by name and from a map with string keys.

Newtypes

A tuple struct with exactly one field is a newtype, like Rust's struct Meters(f64);:

type Meters struct {
    _     struct{} `ron:",tuple"`
    Value float64
}

It encodes as (1.8). With Encoder.SetUnwrapNewtypes(true) it encodes as the plain inner value 1.8 and the output enables unwrap_newtypes. The decoder accepts both (1.8) and 1.8 regardless of extensions.

Example

type Player struct {
    _    struct{} `ron:"Hero"`
    Name string
    Pos  Point
    Size Meters
}

p := Player{Name: "Ferris", Pos: Point{X: 1, Y: 2.5}, Size: Meters{Value: 1.8}}

out, _ := rustyon.Marshal(p)
fmt.Println(string(out))
// (name:"Ferris",pos:(1.0,2.5),size:(1.8))

enc := rustyon.NewEncoder(os.Stdout)
enc.SetStructNames(true)
enc.Encode(p)
// Hero(name:"Ferris",pos:Point(1.0,2.5),size:Meters(1.8))

var back Player
rustyon.Unmarshal([]byte(`Hero(name: "F", pos: Point(3.0, 4.0), size: 2.0)`), &back)
fmt.Println(back.Pos.X, back.Pos.Y, back.Size.Value) // 3 4 2

A struct without any encodable fields encodes as (), or as a bare Name (a unit struct) with struct names on.

Embedded structs

Fields of an embedded struct (or pointer to struct) without a tag name are promoted into the outer struct, as in encoding/json:

type Base struct {
    ID    int
    Label string
}

type Entity struct {
    Base
    Label string // shadows Base.Label
    HP    int
}

out, _ := rustyon.Marshal(Entity{Base: Base{ID: 7, Label: "inner"}, Label: "outer", HP: 10})
fmt.Println(string(out)) // (id:7,label:"outer",hp:10)

var e Entity
rustyon.Unmarshal([]byte(`(id: 1, label: "x", hp: 3)`), &e)
fmt.Printf("%+v\n", e) // {Base:{ID:1 Label:} Label:x HP:3}

Rules:

  • Name conflicts are resolved like encoding/json: the field at the shallowest embedding depth wins; at the same depth a tagged field beats untagged ones; any remaining tie hides the name completely.
  • Embedded pointers are skipped while encoding when nil and allocated while decoding when one of their fields appears. An embedded pointer to an unexported struct type is ignored, because it cannot be allocated.
  • A tag name on an embedded field turns it into a normal nested field: Base `ron:"base"` encodes as base: (id: 1, label: "b").
type A struct{ X, Y int }
type B struct {
    X int
    Z int `ron:"y"`
}
type Both struct {
    A
    B
}

out, _ := rustyon.Marshal(Both{A{1, 2}, B{3, 4}})
fmt.Println(string(out)) // (y:4)

Here x exists in both A and B at the same depth and is dropped; for y, the tagged B.Z beats the untagged A.Y.

Flatten

ron:",flatten" works like serde's #[serde(flatten)]. It has two uses.

Inline struct fields

A field of struct type (or pointer to struct) with the flatten option has its fields written directly in the parent, instead of as a nested struct. Embedded structs without a tag name already behave like this, flatten does the same for named fields.

type Common struct {
    ID   int
    Name string
}

type Outer struct {
    Title string
    Base  Common `ron:",flatten"`
    Last  int
}

out, _ := rustyon.Marshal(Outer{"t", Common{1, "n"}, 9})
fmt.Println(string(out))
// (title:"t",id:1,name:"n",last:9)

var o Outer
err := rustyon.Unmarshal([]byte(`{"last": 3, "name": "z", "title": "q", "id": 4}`), &o)
fmt.Printf("%+v %v\n", o, err)
// {Title:q Base:{ID:4 Name:z} Last:3} <nil>

Fields may come in any order when decoding, and the input may even use map syntax as above. A nil pointer to a flattened struct writes nothing and is allocated on decode as soon as one of its fields appears in the input. The flattened struct keeps its own rename_all.

Catch-all map

A field of type map[string]T with flatten collects every field that no other field matches when decoding, and is written as fields after the regular ones, sorted by key when encoding:

type Meta struct {
    _         struct{} `ron:",rename_all=camelCase"`
    CreatedBy string
}

type Item struct {
    Common `ron:",flatten"`
    Meta   *Meta          `ron:",flatten"`
    Extra  map[string]any `ron:",flatten"` // everything else
}

var it Item
err := rustyon.Unmarshal([]byte(`(id: 7, name: "sword", createdBy: "me", damage: 12, tags: ["a"])`), &it)
fmt.Println(it.ID, it.Name, it.Meta.CreatedBy, it.Extra, err)
// 7 sword me map[damage:12 tags:[a]] <nil>

out, _ := rustyon.Marshal(it)
fmt.Println(string(out))
// (id:7,name:"sword",createdBy:"me",damage:12,tags:["a"])

out, _ = rustyon.MarshalIndent(it, "", "    ")
fmt.Println(string(out))
(
    id: 7,
    name: "sword",
    createdBy: "me",
    damage: 12,
    tags: [
        "a",
    ],
)

The round trip is lossless. Notes:

  • Because the map takes everything else, no field is unknown: DisallowUnknownFields never fires for a struct with a catch-all map.
  • The element type can be concrete. With Rest map[string]int and the input (a: 1, x: "no"), the error names the field: rustyon: cannot unmarshal string into Go value of type int at x.
  • Keys are written as field names, so they must be valid identifiers. Rest: map[string]int{"not valid": 1} makes Marshal fail with rustyon: unsupported value: invalid identifier "not valid".
  • Only maps with string keys can be catch-alls. On a map[int]int field the flatten option is ignored and the field stays an ordinary field, written as skip:{}.
  • A non-flattened struct field stays nested: Sub Common is written as sub:(id:2,name:"x").
  • With Raw as the element type (map[string]rustyon.Raw) the unknown fields are kept as text.

Decoding: exact, then case-insensitive

When decoding, each input field name is looked up exactly first. If that fails, it is matched case-insensitively against the RON names:

var s struct {
    MaxHP int
    Name  string
}
rustyon.Unmarshal([]byte(`(Max_HP: 3, NAME: "x")`), &s)
fmt.Println(s.MaxHP, s.Name) // 3 x

Note that the comparison is against the RON name (max_hp), so MaxHP in the input, without the underscore, does not match. Fields that match nothing are ignored, unless the Decoder has DisallowUnknownFields set.

Clone this wiki locally