module Optionals {
// OPTIONAL BASICS
// Optional{T} is a generic union type that has two cases:
//
// union Optional{T} {
// none, // value not present
// val : T; // value present
// }
fn test1() {
// follow a type with ? to make it optional
let x1 : int?;
// values or none automatically coerce to optional type
let x2 : int? = 1;
let x3 : int? = none;
// optional values are "truthy": true when value is present, false when none
// use ! to extract the value from an optional
if (x3) {
// value present
print("have value! ", x3!);
} else {
print("no value");
}
// use x ?? y to coalesce can optional value x with a default value y
let x4 = x3 ?? -1; // if x3 has a value, extract it, otherwise use -1
// match can be used with optional values
match (x1) {
none => print("no value");
@a : int! => print("have value!", a);
}
}
}