Skip to content

Type Mapping

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

Type Mapping

This page lists how Go values become RON and how RON values become Go values. The rules apply to Marshal, MarshalIndent, Encoder, ToValue (encode direction) and to Unmarshal, Decoder, FromValue (decode direction).

Go to RON (encoding)

Go type RON output Example
bool true, false true
int, int8 ... int64 integer -5
uint, uint8 ... uint64, uintptr integer 18446744073709551615
big.Int, *big.Int integer of any size 170141183460469231731687303715884105727
float32, float64 float, always with a . or exponent 1.5, 2.0, 1e+21
NaN, +Inf, -Inf NaN, inf, -inf -inf
string string with escapes "a\"b\n"
rune (int32) integer, not a char 'x' encodes as 120
[]byte (any slice of a uint8 based type) byte string b"hi\x00"
other slices, arrays list [1,2], ["a","b"]
maps map, entries sorted by key {"a":1,"b":2}
structs struct with snake_case field names, or another naming strategy (a:1,b:2)
rustyon.Raw the stored RON text, laid out like the surrounding output; nil is None (x:3,y:4)
structs with the tuple option tuple (1.0,2.5)
structs without fields unit ()
pointer, non-nil Some(v) Some(7)
pointer, nil None None
interface, nil None None
interface, non-nil the dynamic value (or an enum variant) Circle(radius:1.0)
registered enum variant Name, Name(a, b), Name(field: v) see Enums
registered unit enum value bare identifier Hard
rustyon.Value written as it is Point(x:1)
Marshaler the RON returned by MarshalRON Rgb(255,0,0)
encoding.TextMarshaler string "2026-01-02T03:04:05Z"
chan, func, complex64, complex128 error: *UnsupportedTypeError

Verified outputs from Marshal:

n, _ := new(big.Int).SetString("170141183460469231731687303715884105727", 10)
for _, v := range []any{
    true, -5, uint64(math.MaxUint64), 1.5, 2.0, float32(0.1), math.Inf(-1), math.NaN(),
    "a\"b\n", 'x', []byte("hi\x00"), n,
} {
    out, _ := rustyon.Marshal(v)
    fmt.Println(string(out))
}
true
-5
18446744073709551615
1.5
2.0
0.1
-inf
NaN
"a\"b\n"
120
b"hi\x00"
170141183460469231731687303715884105727
seven := 7
var nilPtr *int
var nilIface any
for _, v := range []any{
    []int{1, 2},
    [2]string{"a", "b"},
    map[string]int{"b": 2, "a": 1},
    map[int]bool{10: true, 9: false, -1: true},
    &seven,
    nilPtr,
    nilIface,
    struct{ A, B int }{1, 2},
    struct{}{},
} {
    out, _ := rustyon.Marshal(v)
    fmt.Println(string(out))
}
[1,2]
["a","b"]
{"a":1,"b":2}
{-1:true,9:false,10:true}
Some(7)
None
None
(a:1,b:2)
()

Details:

  • Floats. A float32 is printed with its shortest float32 representation, so float32(0.1) prints as 0.1. Floats with an integral value get .0 appended (2.0), so they read back as floats.
  • Strings. ", \, newline, carriage return, tab and NUL are escaped as \", \\, \n, \r, \t, \0. Other non-printable characters become \u{...}. Printable Unicode is written as is.
  • Byte strings. Printable ASCII is written as is; ", \, \n, \r, \t are escaped and all other bytes become \xNN. A nil []byte encodes as b"". If the element type is a registered unit enum or has its own marshaler, the slice is a list instead.
  • Maps are sorted so the output is deterministic: strings by value, integers numerically, everything else by its RON text. When keys of different kinds are mixed (for example in a map[any]V), they are grouped by kind first. Map keys can be any encodable type.
  • Identifiers (field names, struct names, variant names) that are reserved words (true, false, inf, NaN, None, Some) or contain characters like -, . or + are written as raw identifiers, for example r#true or r#key-name. A name that cannot be written even as a raw identifier (for example one containing a space) is an *UnsupportedValueError.
  • Cycles. Nesting deeper than 1000 levels returns an *UnsupportedValueError, which catches pointer cycles.

RON to Go (decoding)

Go target Accepted RON values
bool true, false
signed integers integers in range; also chars ('a' is 97)
unsigned integers integers in range; also chars (byte literals like b'a' are integers)
big.Int, *big.Int integers of any size
float32, float64 floats and integers; inf, -inf, NaN. Finite values too large for float32 are an error.
string strings, chars, identifiers
[]byte byte strings, strings, lists or tuples of integers
slices lists, tuples, () (empty) and byte strings (as integers)
arrays lists or tuples with exactly the array length
maps maps; structs (field names become string keys); () (empty)
structs structs (by field name), tuples (by position), maps with string or identifier keys; () or a bare identifier when the struct has no fields
tuple structs with one field (newtypes) the tuple (v) or the plain inner value v
pointers None (nil), Some(v), or plain v
registered enum interfaces variants, see Enums
registered unit enums identifiers or strings naming a variant
rustyon.Value anything; the tree is stored as is
rustyon.Raw anything; the text of the value is stored, see Raw values
a concrete Value type such as rustyon.Struct a value of exactly that kind (use rustyon.Value when the kind can vary)
Unmarshaler anything; UnmarshalRON gets the value re-encoded as compact RON
encoding.TextUnmarshaler strings and identifiers
any (empty interface) anything, see below
other interfaces only registered enums; anything else is an error

Struct names in the input, such as Config(...), are never checked.

The decoder is lenient in a few ways, all of which are verified below:

var s struct {
    Name   string
    Letter string
    Kind   string
    Ratio  float64
    Pair   [2]int
    Data   []byte
}
rustyon.Unmarshal([]byte(`(name: "n", letter: 'x', kind: Fast, ratio: 3, pair: [1, 2], data: "abc")`), &s)
fmt.Printf("%+v\n", s)
// {Name:n Letter:x Kind:Fast Ratio:3 Pair:[1 2] Data:[97 98 99]}

Structs also decode from tuples and maps:

type Pos struct{ X, Y int }
var a, b Pos
rustyon.Unmarshal([]byte(`(1, 2)`), &a)
rustyon.Unmarshal([]byte(`{"x": 3, "y": 4}`), &b)
fmt.Println(a, b) // {1 2} {3 4}

Integer overflow and wrong types produce an *UnmarshalTypeError with the path to the value.

Decoding into any

When the target is an empty interface (any, interface{}), values become plain Go values:

RON Go value in any
() nil
None nil
Some(v) the Go value of v
true, false bool
integer that fits int64 int64
integer that fits only uint64 uint64
larger integer *big.Int
float float64
string string
char rune (int32)
byte string []byte
list, tuple, named tuple []any
map map[any]any
struct, named struct map[string]any
identifier string

Names of tuples and structs are dropped. Decode into a rustyon.Value to keep them.

var v any
rustyon.Unmarshal([]byte(`[
    (), true, 1, 18446744073709551615, 100000000000000000000000,
    1.5, "s", 'c', b"\x01", [1], (1, 2), {1: "one"}, (x: 1),
    Point(x: 1), Red, None, Some(5),
]`), &v)
for _, e := range v.([]any) {
    fmt.Printf("%T %v\n", e, e)
}
<nil> <nil>
bool true
int64 1
uint64 18446744073709551615
*big.Int 100000000000000000000000
float64 1.5
string s
int32 99
[]uint8 [1]
[]interface {} [1]
[]interface {} [1 2]
map[interface {}]interface {} map[1:one]
map[string]interface {} map[x:1]
map[string]interface {} map[x:1]
string Red
<nil> <nil>
int64 5

Map keys in a map[any]T must be comparable in Go: a list or map used as a key is an *UnmarshalTypeError (map key is not comparable in Go), never a panic. Integer keys too large for uint64 become their decimal string, because *big.Int keys would compare by pointer.

Pointers and Option

A pointer is RON's Option:

  • encoding: nil is None, anything else is Some(v);
  • decoding: None sets the pointer to nil, Some(v) and a plain v both allocate and decode v.
type Settings struct {
    Volume *int
    Muted  *bool
    Name   *string
}
var s Settings
rustyon.Unmarshal([]byte(`(volume: Some(80), muted: None, name: "implicit")`), &s)
fmt.Println(*s.Volume, s.Muted == nil, *s.Name) // 80 true implicit

Nested pointers nest options: **int is Option<Option<i32>>, written as Some(Some(3)).

*big.Int is the exception: it is the usual way to hold a big integer in Go, so it encodes as a plain integer, not as an Option.

A non-pointer target does not accept Some(...): decoding Some(5) into an int fails with cannot unmarshal Some into Go value of type int.

implicit_some

RON's implicit_some extension lets Some(x) be written as x. The decoder always accepts the plain form for pointers, whether or not the document enables the extension. The encoder writes it when asked:

n := 3
enc := rustyon.NewEncoder(os.Stdout)
enc.SetImplicitSome(true)
enc.Encode(struct{ A, B *int }{&n, nil})
// #![enable(implicit_some)](a:3,b:None)

Byte strings

[]byte encodes as a RON byte string b"...". On decoding, a []byte accepts byte strings, regular strings (their UTF-8 bytes) and lists or tuples of integers. A [N]byte array is treated like any other array: it encodes as a list of integers and decodes from a list, tuple or byte string of exactly N elements.

Big integers

RON integers go up to 128 bits (i128, u128), which do not fit into Go's builtin integer types. Use big.Int or *big.Int fields, or decode into a rustyon.Value and use rustyon.Int.

var s struct {
    Small int64
    Huge  *big.Int
}
rustyon.Unmarshal([]byte(`(small: 0x7f, huge: 340282366920938463463374607431768211455u128)`), &s)
fmt.Println(s.Small, s.Huge)
// 127 340282366920938463463374607431768211455

TextMarshaler and TextUnmarshaler

Types implementing encoding.TextMarshaler encode as a RON string. Types whose pointer implements encoding.TextUnmarshaler decode from a string or an identifier. This covers time.Time, netip.Addr and similar standard library types. (time.Duration has no text methods, so it is an integer of nanoseconds.)

// Version implements encoding.TextMarshaler and encoding.TextUnmarshaler.
type Version struct{ Major, Minor int }

func (v Version) MarshalText() ([]byte, error) {
    return []byte(fmt.Sprintf("%d.%d", v.Major, v.Minor)), nil
}

func (v *Version) UnmarshalText(b []byte) error {
    major, minor, ok := strings.Cut(string(b), ".")
    if !ok {
        return errors.New("bad version")
    }
    var err error
    if v.Major, err = strconv.Atoi(major); err != nil {
        return err
    }
    v.Minor, err = strconv.Atoi(minor)
    return err
}

type Release struct {
    Version Version
    Date    time.Time
}

out, _ := rustyon.Marshal(Release{Version{1, 2}, time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)})
fmt.Println(string(out))
// (version:"1.2",date:"2026-01-02T03:04:05Z")

var back Release
rustyon.Unmarshal(out, &back)
fmt.Println(back.Version.Minor, back.Date.Year()) // 2 2026

For a type with text methods that is also a registered unit enum, the enum registration wins. big.Int is always an integer even though it has text methods.

Marshaler and Unmarshaler

For full control, implement the RON interfaces:

type Marshaler interface {
    MarshalRON() ([]byte, error)
}

type Unmarshaler interface {
    UnmarshalRON([]byte) error
}
  • MarshalRON must return a single valid RON value. The output is parsed and embedded; if it is invalid or the method returns an error, Marshal returns a *MarshalerError.
  • UnmarshalRON receives the value re-encoded as compact RON. Comments and literal spellings from the source are not preserved. The method is called at most once per value, also when a later part of the document turns out to be invalid.
  • Marshaler is checked before TextMarshaler; both may use value or pointer receivers.
// RGB is written as Rgb(r, g, b) by its own Marshaler.
type RGB struct{ R, G, B uint8 }

func (c RGB) MarshalRON() ([]byte, error) {
    return []byte(fmt.Sprintf("Rgb(%d, %d, %d)", c.R, c.G, c.B)), nil
}

func (c *RGB) UnmarshalRON(data []byte) error {
    v, err := rustyon.Parse(data)
    if err != nil {
        return err
    }
    t, ok := v.(rustyon.Tuple)
    if !ok || t.Name != "Rgb" || len(t.Values) != 3 {
        return fmt.Errorf("expected Rgb(r, g, b), got %s", data)
    }
    parts := []*uint8{&c.R, &c.G, &c.B}
    for i, p := range parts {
        n, _ := t.Values[i].(rustyon.Int).Uint64()
        *p = uint8(n)
    }
    return nil
}

out, _ := rustyon.Marshal(map[string]RGB{"red": {255, 0, 0}})
fmt.Println(string(out)) // {"red":Rgb(255,0,0)}

var m map[string]RGB
rustyon.Unmarshal([]byte(`{"teal": Rgb(0, 128, 128)}`), &m)
fmt.Println(m["teal"]) // {0 128 128}

Errors returned by UnmarshalRON are passed through unchanged.

Value passthrough

A field of type rustyon.Value receives the parsed tree unchanged, including struct names and map order, and is written back as it is. This is useful for plugin configuration or other parts whose shape you do not know in advance.

type Plugin struct {
    Name   string
    Config rustyon.Value // kept as a tree, shape not known in advance
}
var p Plugin
rustyon.Unmarshal([]byte(`(name: "lint", config: Rules(max: 3, deny: [Unused]))`), &p)
s := p.Config.(rustyon.Struct)
fmt.Println(s.Name, len(s.Fields)) // Rules 2

out, _ := rustyon.Marshal(p)
fmt.Println(string(out)) // (name:"lint",config:Rules(max:3,deny:[Unused]))

See Value Tree for working with the tree.

Raw values

rustyon.Raw is a []byte that holds one RON value as text, like json.RawMessage. Use it to delay decoding of part of a document until you know its type, or to pass a value through. Unlike a Value, no tree is built: the text is copied.

type Envelope struct {
    Kind    string
    Payload rustyon.Raw // decoded once Kind is known
}

var e Envelope
err := rustyon.Unmarshal([]byte(`(kind: "point", payload: (x: 3, y: 4 /* kept */))`), &e)
fmt.Printf("%s %v\n", e.Payload, err)
// (x: 3, y: 4 /* kept */) <nil>

var p struct{ X, Y int }
fmt.Println(e.Payload.Decode(&p), p) // <nil> {3 4}

out, _ := rustyon.Marshal(e)
fmt.Println(string(out))
// (kind:"point",payload:(x:3,y:4))

Rules:

  • Decoding captures the text of the value exactly as written, comments included, as long as the document enables no extensions. With #![enable(...)] the value is stored as compact RON printed from its parse tree, so that the text means the same without the extensions: payload: Some(1) /* c */ under implicit_some is stored as Some(1).

  • Encoding requires the text to be a single valid RON value, otherwise Marshal fails. The value is parsed and written in the layout of the surrounding output, so comments and spacing inside it are not kept, as the output above shows. A nil Raw is written as None.

    rustyon: error calling MarshalRON for type rustyon.Raw: rustyon: syntax error at 1:4: unexpected end of input
    
  • Raw.Decode(v) is Unmarshal(raw, v).

  • Raw works anywhere a value does: struct fields, slice elements, map values (map[string]rustyon.Raw) and as the element type of a flatten catch-all map.

  • Although Raw is a byte slice, it is written as RON, not as a byte string, because it implements Marshaler.

A typical use is dispatching on a tag:

type Point struct{ X, Y int }
type Config struct {
    MaxFPS int
    Title  string
}

docs := `(kind: "point", payload: (x: 1, y: 2))
(kind: "config", payload: (max_fps: 60, title: "T"))`
dec := rustyon.NewDecoder(strings.NewReader(docs))
for dec.More() {
    env, err := rustyon.DecodeAs[Envelope](dec)
    if err != nil {
        log.Fatal(err)
    }
    switch env.Kind {
    case "point":
        pt, err := rustyon.UnmarshalAs[Point](env.Payload)
        fmt.Println("point", pt, err)
    case "config":
        c, err := rustyon.UnmarshalAs[Config](env.Payload)
        fmt.Println("config", c, err)
    }
}
point {1 2} <nil>
config {60 T} <nil>

Generic helpers

UnmarshalAs[T] and DecodeAs[T] return the value instead of filling a pointer:

func UnmarshalAs[T any](data []byte, opts ...DecodeOptions) (T, error)
func DecodeAs[T any](dec *Decoder) (T, error)
c, err := rustyon.UnmarshalAs[Config]([]byte(`(max_fps: 60)`))
fmt.Println(c, err) // {60 } <nil>

UnmarshalAs takes an optional DecodeOptions (only the first is used) for field naming, unknown field handling and a registry, exactly like UnmarshalWith:

c, err = rustyon.UnmarshalAs[Config]([]byte(`(maxFps: 61, extra: 1)`),
    rustyon.DecodeOptions{FieldNaming: rustyon.CamelCase, DisallowUnknownFields: true})
fmt.Println(c, err)
// {61 } rustyon: unknown field "extra" for type main.Config

_, err = rustyon.UnmarshalAs[Config]([]byte(`(max_fps: "x")`))
fmt.Println(err)
// rustyon: cannot unmarshal string into Go value of type int at max_fps

On error, the returned value holds whatever was decoded before the error, as with Unmarshal. DecodeAs reads the next value from a Decoder, as Decode does, and returns io.EOF when the stream is finished.

Clone this wiki locally