Skip to content

Getting Started

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

Getting Started

This page walks through the core API. Every example on this page compiles and prints exactly the output shown.

go get github.com/peltonapp/rustyon-go
import "github.com/peltonapp/rustyon-go" // package rustyon

Unmarshal

rustyon.Unmarshal(data []byte, v any) error parses one RON document and stores it in the value v points to. It works like encoding/json: pass a non-nil pointer.

type Config struct {
    WindowTitle string
    WindowSize  [2]int
    MaxFPS      *int
    Tags        []string `ron:"labels,omitempty"`
}

data := []byte(`
// game.ron
Config(
    window_title: "Rusty Game",
    window_size: (800, 600),
    max_fps: Some(60),
    labels: ["fast", "fun"],
)`)

var c Config
if err := rustyon.Unmarshal(data, &c); err != nil {
    log.Fatal(err)
}
fmt.Println(c.WindowTitle, c.WindowSize, *c.MaxFPS, c.Tags)
// Rusty Game [800 600] 60 [fast fun]

Things to notice:

  • WindowTitle matches window_title without a tag. Go field names are converted to snake_case (see Struct Tags).
  • The struct name Config(...) in the input is accepted but not checked against the Go type.
  • Unmarshal and Decoder decode straight from the source text into your Go value, without building a Value tree first. The tree is only built for the parts that need it: values going into any, a rustyon.Value, a registered enum, or a type with UnmarshalRON or UnmarshalText.
  • If decoding fails, the target may be partially modified: fields decoded before the error keep their new values. Decode into a fresh variable if you need all or nothing.
  • UnmarshalRON and UnmarshalText methods run at most once per value, even when a later part of the input is invalid.
  • [2]int decodes from the tuple (800, 600). Arrays and slices accept both lists and tuples.
  • *int is an Option: Some(60), None, or a plain 60 all work.
  • Unknown fields are ignored. Use a Decoder with DisallowUnknownFields to reject them.
  • Field names match exactly first, then case-insensitively. Use UnmarshalWith for other naming styles such as camelCase.
  • rustyon.UnmarshalAs[Config](data) returns the value instead of filling a pointer.

The full set of conversions is on Type Mapping.

Marshal and MarshalIndent

rustyon.Marshal(v any) ([]byte, error) returns the compact encoding. rustyon.MarshalIndent(v any, prefix, indent string) writes one element per line, starting each line with prefix followed by one indent per nesting level. An empty indent in MarshalIndent defaults to four spaces.

fps := 144
c := Config{WindowTitle: "Rusty Game", WindowSize: [2]int{800, 600}, MaxFPS: &fps}

out, _ := rustyon.Marshal(c)
fmt.Println(string(out))

out, _ = rustyon.MarshalIndent(c, "", "    ")
fmt.Println(string(out))

Output:

(window_title:"Rusty Game",window_size:[800,600],max_fps:Some(144))
(
    window_title: "Rusty Game",
    window_size: [
        800,
        600,
    ],
    max_fps: Some(144),
)

Notes:

  • Struct names are not written by default; an anonymous struct (...) is valid RON for any Rust struct. Use Encoder.SetStructNames(true) to write Config(...).
  • Go arrays encode as lists. To get a RON tuple such as (800, 600), use a tuple struct (see Struct Tags).
  • The labels field is skipped because of omitempty.
  • Pretty output uses trailing commas. Tuples whose elements are all scalars (or nested scalar tuples and options) stay on one line, such as pos: (1, 2).
  • Neither function appends a trailing newline.
  • For more layout control (compact lists, depth limit, escaped non-ASCII, numbered list elements) use MarshalWithConfig, see Pretty Printing.

Decoder

rustyon.NewDecoder(r io.Reader) returns a *Decoder. A decoder reads all of r on the first call to Decode or More, then hands out one value per Decode call. The input may hold several values separated by whitespace or comments, and #![enable(...)] attributes are accepted before the first value.

Method Effect
Decode(v any) error Decodes the next value into v. Returns io.EOF when no values are left.
More() bool Reports whether another value follows. If reading or the first tokens fail, it returns true so that Decode reports the error.
DisallowUnknownFields() Makes Decode return an *UnknownFieldError for struct fields without a Go counterpart.
SetRegistry(r *Registry) Uses r for enums instead of DefaultRegistry. nil selects DefaultRegistry.
SetFieldNaming(n NamingStrategy) Matches field names without a tag with n instead of snake_case. See Struct Tags.

For a single value, rustyon.DecodeAs[T](dec) returns the value instead of filling a pointer, see Type Mapping.

Reading a stream of values

src := `#![enable(implicit_some)]
(name: "first")   // one value
(name: "second")  /* another */
(name: "third")
`
type Entry struct{ Name string }

dec := rustyon.NewDecoder(strings.NewReader(src))
for dec.More() {
    var e Entry
    if err := dec.Decode(&e); err != nil {
        log.Fatal(err)
    }
    fmt.Println(e.Name)
}
var e Entry
fmt.Println(dec.Decode(&e) == io.EOF)

Output:

first
second
third
true

Rejecting unknown fields

type Server struct {
    Host string
    Port int
}
dec := rustyon.NewDecoder(strings.NewReader(`(host: "localhost", port: 8080, debug: true)`))
dec.DisallowUnknownFields()

var s Server
err := dec.Decode(&s)
fmt.Println(err)
// rustyon: unknown field "debug" for type main.Server

var ufe *rustyon.UnknownFieldError
if errors.As(err, &ufe) {
    fmt.Println("unknown field:", ufe.Field) // unknown field: debug
}

Unmarshal itself has no option for this; use a Decoder when you need it.

Encoder

rustyon.NewEncoder(w io.Writer) returns a *Encoder. Encode(v any) error writes the encoding of v followed by a newline. The setters change all following Encode calls.

Method Effect
SetIndent(prefix, indent string) Pretty prints like MarshalIndent. An empty indent switches back to compact output.
SetStructNames(on bool) Writes struct names: Config(port: 80) instead of (port: 80). Unit structs become a bare Name.
SetImplicitSome(on bool) Writes non-nil pointers as the plain value instead of Some(value) and adds #![enable(implicit_some)] to the output.
SetUnwrapNewtypes(on bool) Writes tuple structs with a single field as their inner value and adds #![enable(unwrap_newtypes)] to the output.
SetRegistry(r *Registry) Uses r for enums instead of DefaultRegistry. nil selects DefaultRegistry.
SetFieldNaming(n NamingStrategy) Names fields without a tag with n instead of snake_case. See Struct Tags.
SetPrettyConfig(cfg *PrettyConfig) Pretty prints with a full layout configuration. nil switches back to compact output. Replaces SetIndent.
type Meters struct {
    _     struct{} `ron:",tuple"`
    Value float64
}

type Window struct {
    Title  string
    Width  *int
    Margin Meters
}

w := 640
win := Window{Title: "main", Width: &w, Margin: Meters{Value: 1.5}}

enc := rustyon.NewEncoder(os.Stdout)
enc.Encode(win)

enc.SetStructNames(true)
enc.SetImplicitSome(true)
enc.SetUnwrapNewtypes(true)
enc.SetIndent("", "    ")
enc.Encode(win)

Output:

(title:"main",width:Some(640),margin:(1.5))
#![enable(implicit_some, unwrap_newtypes)]
Window(
    title: "main",
    width: 640,
    margin: 1.5,
)

In compact mode the extension header is written directly in front of the value, for example #![enable(implicit_some)]Window(title:"main",width:640).

Nested options keep their inner Some under SetImplicitSome, so a pointer to a nil pointer is written as Some(None) and round trips correctly.

Options without an Encoder or Decoder

Marshal and Unmarshal have no options. When you want some for a single call, use MarshalWith and UnmarshalWith. Their option structs behave like Marshal and Unmarshal when left at the zero value.

EncodeOptions field Same as
FieldNaming NamingStrategy Encoder.SetFieldNaming
StructNames bool Encoder.SetStructNames
ImplicitSome bool Encoder.SetImplicitSome
UnwrapNewtypes bool Encoder.SetUnwrapNewtypes
Registry *Registry Encoder.SetRegistry; nil is DefaultRegistry
Pretty *PrettyConfig Encoder.SetPrettyConfig; nil is compact output
DecodeOptions field Same as
FieldNaming NamingStrategy Decoder.SetFieldNaming
DisallowUnknownFields bool Decoder.DisallowUnknownFields
Registry *Registry Decoder.SetRegistry; nil is DefaultRegistry
type Window struct {
    WindowTitle string
    MaxFPS      int
}

out, _ := rustyon.MarshalWith(Window{"main", 60}, rustyon.EncodeOptions{
    FieldNaming: rustyon.CamelCase,
    StructNames: true,
    Pretty:      &rustyon.PrettyConfig{Indent: "  "},
})
fmt.Println(string(out))

var w Window
err := rustyon.UnmarshalWith(out, &w, rustyon.DecodeOptions{FieldNaming: rustyon.CamelCase, DisallowUnknownFields: true})
fmt.Println(w, err)
Window(
  windowTitle: "main",
  maxFps: 60,
)
{main 60} <nil>

MarshalWithConfig(v, cfg) is shorthand for MarshalWith with only Pretty set. For a single value without a pointer, UnmarshalAs[T](data) is Unmarshal that returns the value. See Type Mapping.

Custom registries

Enums registered with rustyon.RegisterEnum go into rustyon.DefaultRegistry, which Marshal, Unmarshal and all encoders and decoders use by default. To keep a separate set of enums, create a registry and pass it to an Encoder and Decoder:

type Animal interface{ isAnimal() }
type Cat struct{ Lives int }

func (Cat) isAnimal() {}

reg := rustyon.NewRegistry()
rustyon.RegisterEnumIn[Animal](reg, rustyon.Variant[Cat]("Cat"))

var buf strings.Builder
enc := rustyon.NewEncoder(&buf)
enc.SetRegistry(reg)
enc.Encode([]Animal{Cat{Lives: 9}})
fmt.Print(buf.String()) // [Cat(lives:9)]

dec := rustyon.NewDecoder(strings.NewReader(buf.String()))
dec.SetRegistry(reg)
var zoo []Animal
dec.Decode(&zoo)
fmt.Printf("%#v\n", zoo[0]) // main.Cat{Lives:9}

Marshal, MarshalIndent, Unmarshal, ToValue and FromValue always use DefaultRegistry. See Enums for the full story.

Next steps

Clone this wiki locally