Language Design: Unified Condition Expressions

Comparison with Rust

Published on 2022-11-07.
simple if expression
if x == 1.0 { "a" }
else        { "z" }

This translates straight-forward to Rust:

if x == 1.0 { "a" }
else        { "z" }
multiple cases, equality relation
if x
... == 1.0 { "a" }
... == 2.0 { "b" }
else       { "z" }

In Rust, using match is idiomatic:

match x {
  1.0 => "a",
  2.0 => "b",
  _   => "z"
}
multiple cases, any other relation
if x
... == 1.0 { "a" }
... != 2.0 { "b" }
else       { "z" }

Rust requires the use match with guards (match on its own only supports equality relations), or an if expression:

match x {
  1.0 => "a"                           if x == 1.0      { "a" }
  x if x != 2.0 => "b"                 else if x != 2.0 { "b" }
  _ => "z"                             else             { "z" }
multiple cases, method calls
if x
... .isInfinite { "a" }
... .isNaN      { "b" }
else            { "z" }

In Rust one would use match with guards, or an if expression:

match x {
  x if x.is_infinite() => "a"          if x.is_infinite() { "a" }
  x if x.is_nan() => "b"               else if x.is_nan() { "b" }
  _ => "z"                             else               { "z" }
}
“if-let”, statement12
if opt_number is Some(i) { /* use `i` */ }

Rust requires a special construct to pattern match or introduce bindings:

if let Some(i) = opt_number { /* use `i` */ }
“if-let”, expression12
let result = if opt_number
  is Some(i) { i }
  else       { 0 }

Rust uses the let-equals-if-let-equals pattern:

let result = if let Some(i) = opt_number {
  i
} else {
  0
}
“if-let” chains3
let result = if opt_number.contains(1.0) { 1.0 } else { 0 }

Rust proposes the if-let chains syntax:

let result = if let Some(i) && i == 1.0 = opt_number {
  i
} else {
  0
}
“let-else”45
let i = if opt_number
  is Some(i) { i }
  else       { return 0 }

Rust’s let-else allows binding a fallible pattern without introducing nesting:

let Some(i) = opt_number else {
    return 0;
};
  1. Rust if-let – https://doc.rust-lang.org/book/second-edition/ch06-03-if-let.html  2

  2. Swift if-let – https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html  2

  3. Rust if-let chains – https://github.com/rust-lang/rust/issues/53667 

  4. Rust let-else – https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#let-else-statements 

  5. Swift guard-let – https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html