Skip to content

Control flow

Write if cond { … }, while cond { … }, match value { … }. Parentheses are for grouping only: (1 + 2) * 3.

if is an expression when both branches exist:

fn tag(age: int) -> String {
return if age >= 18 { "adult" } else { "minor" }
}
fn main(caps: Caps) -> int {
print tag(20)
return 0
}

Statement form still works: if cond { … } else { … }.

fn sum_list(xs: Array<int>) -> int {
var total = 0
for x in xs {
total = total + x
}
return total
}
fn sum_to(n: int) -> int {
var total = 0
for i in 0..n {
total = total + i
}
return total
}

0..n means 0 <= i < n.

Index must be var (not let):

fn sum_c(n: int) -> int {
var total = 0
for var i = 0; i < n; i++ {
total = total + i
}
return total
}
// fragment-only
fn odd_sum_until(limit: int) -> int {
var i = 0
var acc = 0
while i < limit {
i += 1
if i % 2 == 0 {
continue
}
if i > 10 {
break
}
acc = acc + i
}
return acc
}

Keywords, not C punctuation:

// fragment-only
if a > 0 and not done {
return 1
}
if a == 0 or b == 0 {
return 2
}
enum Shape {
Circle(int),
Rect(int, int)
}
fn area(s: Shape) -> int {
return match s {
Circle(r) => 3 * r * r,
Rect(w, h) => w * h
}
}

Match must be exhaustive. Arms may be blocks (last expression is the value):

// fragment-only
let v = match o {
Some(x) => {
print x
x + 1
},
None => 0
}
// fragment-only
fn area(s: Shape) -> int {
return switch s {
case Circle(r): 3 * r * r,
case Rect(w, h): w * h,
}
}

Same exhaustiveness as match — see Syntax ergonomics.