Repository navigation
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-goimport "github.com/peltonapp/rustyon-go" // package rustyonrustyon.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:
-
WindowTitlematcheswindow_titlewithout a tag. Go field names are converted tosnake_case(see Struct Tags). - The struct name
Config(...)in the input is accepted but not checked against the Go type. -
UnmarshalandDecoderdecode straight from the source text into your Go value, without building aValuetree first. The tree is only built for the parts that need it: values going intoany, arustyon.Value, a registered enum, or a type withUnmarshalRONorUnmarshalText. - 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.
-
UnmarshalRONandUnmarshalTextmethods run at most once per value, even when a later part of the input is invalid. -
[2]intdecodes from the tuple(800, 600). Arrays and slices accept both lists and tuples. -
*intis anOption:Some(60),None, or a plain60all work. - Unknown fields are ignored. Use a
DecoderwithDisallowUnknownFieldsto reject them. - Field names match exactly first, then case-insensitively. Use
UnmarshalWithfor other naming styles such ascamelCase. -
rustyon.UnmarshalAs[Config](data)returns the value instead of filling a pointer.
The full set of conversions is on Type Mapping.
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. UseEncoder.SetStructNames(true)to writeConfig(...). - Go arrays encode as lists. To get a RON tuple such as
(800, 600), use a tuple struct (see Struct Tags). - The
labelsfield is skipped because ofomitempty. - 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.
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.
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
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.
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.
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.
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.
- Type Mapping for every Go type
-
Struct Tags for naming strategies,
flattenand tags - Pretty Printing for output layout
- Enums for Rust enums, including serde's tagged and untagged forms
- Value Tree for documents of unknown shape
- Errors for error handling
rustyon is licensed under the BSD-3-Clause license. It is an independent implementation of RON and is not affiliated with the ron-rs project.