Xo is experimental. The source code is not public yet; it will be soon. Read the release notes
Menu · No nil: optionals

Docs

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 ?? default supplies a fallback.
  • In a function that returns an optional, opt? gives the value or returns None at once, as in port.
  • A plain T is accepted where a T? is expected (email: Some(...) could be written email: "..."). That is one of only three implicit conversions in the language.