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:
$ cue mod edit --language-version v0.16.0You 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:
// No experiment required
package p
a?: int
if a != _|_ {
b: a + 1
}@experiment(try)
package p
a?: int
try {
b: a? + 1
}$ cue export
{}A try clause can also bind an identifier to a value
for use in subsequent clauses and the comprehension body:
@experiment(try)
package p
a?: int
try x = {
value: a? + 1
} if x.value > 5 {
b: x
}$ cue export
{}Finally, you can also use an else clause for a fallback value:
@experiment(try)
package p
a?: int
try {
b: a? + 1
} else {
b: -1
}$ cue export
{
"b": -1
}