enum represents one of a fixed set of cases. Res[T, E] represents a value
or a checked error, and Opt[T] represents a value that may be absent. They
make routine data failure visible in the program; the language does not use
exceptions for it.
Results
No output.
- Executed source spans appear here.
The fixture prints release, none, 5, and InvalidUtf8. Change
Release.Published("release") to Release.Draft, then Run: the first output
follows the other match arm.
Match every case
enum State { Idle, Moving(f32) }
let label = match State.Moving(1:f32) {
State.Idle => "idle",
State.Moving(speed) => "moving",
};Construct a named case with State.Moving(1:f32). A match must cover every
case; an arm wholly covered by earlier arms is a compile error. Cases for built-in
results are bare: Ok(value), Err(error), Some(value), and None.
Match values and typed payloads
let status = 2;
let label = match status {
0 => "idle",
1 => "running",
_ => "unknown",
};
print(label);Literal patterns compare values. _ accepts any remaining value without binding
it. Named patterns bind a value with its checked type:
type Reading { value: f64; }
enum Sample { Known(Reading), Missing }
let sample = Sample.Known(Reading { value: 3 });
let number = match sample {
Sample.Known(Reading { value }) => value,
Sample.Missing => 0,
};
print(number);Record patterns name a declared type and unpack its fields. Nested patterns retain their payload types; matching does not dynamically cast a value.
Propagate compatible failures
Checked numeric and tensor arithmetic returns Res[..., DataError]. The ?
operator unwraps Ok or Some; on Err or None, it returns that value from
the enclosing function. It is valid only when the enclosing Res or Opt
return type is compatible.
func checked_sum(a: f32, b: f32) -> Res[f32, DataError] {
ret Ok((a + b)?);
}
print(checked_sum(1:f32, 2:f32)?);The top-level initializer is implicitly Res[Unit, DataError]. A lifecycle
callback returns Unit or Res[Unit, DataError]; a returned Err rejects the
host transaction and rolls it back. An Err nested inside an ordinary value is
just data until the program matches or propagates it.
DataError is an SDK enum whose cases can be matched in Rust as well as in
Konjure source. It records data failures such as malformed UTF-8, incompatible
shapes, bounds, overflow, and non-finite arithmetic without giving source code
an unchecked host exception path.