luminyra
Guides

Option and missing values

Build an Option from a configuration lookup, change its value type, and handle missing JSON fields.

Lookups and default values

The example looks up configuration in a map and trims whitespace. OptionOf accepts the result and a presence flag. Option.Filter treats an empty string as absent. When reading the host and mode, Option.Or uses the fallback only when the value is missing.

fp/examples/option/main.go
// Turn the comma-ok idiom into an Option and treat blank values as absent.
lookup := func(key string) fp.Option[string] {
	v, ok := env[key]
	return fp.OptionOf(strings.TrimSpace(v), ok).Filter(func(s string) bool { return s != "" })
}

host := lookup("HOST").Or("localhost")
mode := lookup("MODE").Or("production")
View on GitHub

Change types in a chain

Option.AndThen lets the parser return another Option, so missing fields and parse failures flow through the same chain. Option.Map transforms a value when it exists. The example doubles the parsed worker count.

fp/examples/option/main.go
// Map and AndThen are generic methods, so the chain turns a string into an
// int directly.
parseInt := func(s string) fp.Option[int] {
	n, err := strconv.Atoi(s)
	return fp.OptionOf(n, err == nil)
}
workers := lookup("WORKERS").AndThen(parseInt).Map(func(n int) int { return n * 2 })
debug := lookup("DEBUG").Map(func(s string) bool { return s == "1" })
View on GitHub

JSON and iterators

A missing nickname encodes as JSON null. Missing or null fields decode to an absent value, which Option.IsNone can check. When used as an iterator, Option.All yields once if a value exists and yields nothing otherwise.

fp/examples/option/main.go
// An empty Option encodes as null; null or a missing field decodes as None.
out, err := json.Marshal([]Profile{
	{Name: "alice", Nickname: fp.Some("ali")},
	{Name: "bob"},
})
if err != nil {
	panic(err)
}
fmt.Println(string(out))

var p Profile
if err := json.Unmarshal([]byte(`{"name":"carol"}`), &p); err != nil {
	panic(err)
}
fmt.Println(p.Name, p.Nickname, p.Nickname.IsNone())
View on GitHub

On this page