Requires CUE v0.16.0 or later

CUE v0.16.0-alpha.2 introduced the “try” experiment, which adds a try clause in comprehensions as well as the use of ? in field references.

This addition to the language intends to provide a more concise syntax for handling missing optional fields, reducing the boilerplate of explicit error checks.

To use this language feature, update your module to target language version v0.16.0 or later with cue mod edit:

TERMINAL
$ cue mod edit --language-version v0.16.0

You can now enable the experiment on a per-file basis using @experiment(try).

A try clause can be used to improve the conditional definition of a field based on the presence of another field:

without-try.cue
// No experiment required

package p

a?: int
if a != _|_ {
	b: a + 1
}
with-try.cue
@experiment(try)

package p

a?: int
try {
    b: a? + 1
}
TERMINAL
$ cue export
{}

A try clause can also bind an identifier to a value for use in subsequent clauses and the comprehension body:

try-with-bind.cue
@experiment(try)

package p

a?: int

try x = {
    value: a? + 1
} if x.value > 5 {
    b: x
}
TERMINAL
$ cue export
{}

Finally, you can also use an else clause for a fallback value:

try-with-else.cue
@experiment(try)

package p

a?: int

try {
    b: a? + 1
} else {
    b: -1
}
TERMINAL
$ cue export
{
    "b": -1
}