if Expression Types

2026-08-25

The types of both branches of an if expression must match. But while

let my_bool = true;
let x = if my_bool { 5; };

will compile, x is not of type i32 (as you might have expected) but of type (), because '5;' is a statement and every statement returns () (the only value of type ()), and every if expression that omits its else branch evaluates to ().

Also, be aware that

let my_bool = true;
let x = if my_bool { 5; } else { "hello"; };

will compile for the same reason, but x will again be () of type (). Omitting the semicola within both branches:

let my_bool = true;
let x = if my_bool { 5 } else { "hello" };

will not compile (as expected) because of the type mismatch between if's branches.