Pass KnownFields() to catch typos such as replica.
go mod init demo go get oneyaml.dev/go
Requires Go 1.24 or later.
package main import ( "fmt" yaml "oneyaml.dev/go" ) func main() { var cfg struct{ Replicas int } err := yaml.Unmarshal( []byte("replica: 3\n"), &cfg, yaml.KnownFields(), ) if err != nil { fmt.Println(err); return } fmt.Println(cfg.Replicas) }
go run . prints:
oneyaml: line 1, column 1: /replica: field "replica" not found in type struct { Replicas int }Unzip the example, then go run ..
The decoder expects replicas, the lowercase name of Replicas, not replica.
The decoder can fill other fields before returning an error. Decode into a fresh struct and use it only after a successful read.
Variations
Correct the key. Replace []byte("replica: 3\n") with:
[]byte("replicas: 3\n")The same program now prints 3.
Related recipes
The short answer
Pass KnownFields() to Unmarshal when decoding into a struct. If a key doesn’t match a field, the decoder reports the location and the path, such as /replica in the example. The read still processes the rest of the document, so the returned error, not the contents of the struct, is what tells you whether the configuration is safe to use.
How do I make Go’s YAML decoder reject unknown fields?
Without KnownFields(), an unmatched key in a struct is skipped. That means a misspelling can quietly leave the expected field at its zero value. Use KnownFields() for a config format whose keys you control. If your field has an explicit yaml tag, the tag determines the key name. A map is different: its keys come from the YAML, so the keys in a map[string]any aren’t checked against a list of struct fields.
If you use Decoder.KnownFields(true), pass KnownFields() to Unmarshal for the same unknown-field check; see the migration guide.
For a command-line tool, the full error message may be all you need. If you need to distinguish an unknown key from another decode error, the strict configuration guide shows how to match ErrUnknownField and how to list each reported mismatch with its position.
Does strict decoding catch missing YAML fields?
No. An unknown field is a key that’s present in the file but absent from the struct’s allowed names. A missing field is the opposite. KnownFields() only checks keys the decoder encounters. If replicas is required, check it after decoding; if both an omitted value and an explicit zero have different meanings in your app, represent presence separately, for example with a pointer field. Check application rules after decoding too: a correctly spelled integer is not necessarily a valid replica count.