No nil: optionals
There is no nil in Xo. A value that may be missing has type T? (an
Option[T]): either Some(v) or None, and the compiler makes you look
before you use it.
optionals/main.xo
struct User { name: Str, email: Str? }
fn contact(u: User) -> Str {
if let Some(e) = u.email { "mail ${e}" } else { "no email for ${u.name}" }
}
fn port(s: Str) -> Int? {
let n = Int.parse(s.trim())?
if n > 0 && n < 65536 { n } else { None }
}
fn main(os: Os) {
let a = User{name: "Ada", email: Some("ada@example.com")}
let b = User{name: "Bob", email: None}
os.stdio.println(contact(a))
os.stdio.println(contact(b))
os.stdio.println(b.email ?? "unknown")
for s in [" 8080 ", "http", "70000"] {
os.stdio.println("port(\"${s}\") = ${port(s) ?? -1}")
}
}Output:
mail ada@example.com
no email for Bob
unknown
port(" 8080 ") = 8080
port("http") = -1
port("70000") = -1
if let Some(e) = opt { ... }runs only when there is a value.opt ?? defaultsupplies a fallback.- In a function that returns an optional,
opt?gives the value or returnsNoneat once, as inport. - A plain
Tis accepted where aT?is expected (email: Some(...)could be writtenemail: "..."). That is one of only three implicit conversions in the language.