Expand description
Evaluate a block if a condition holds.
if is a familiar construct to most programmers, and is the main way you’ll often do logic inyour code. However, unlike in most languages,if blocks can also act as expressions.
if1==2{println!("whoops, mathematics broke");}else{println!("everything's fine!");}letgreeting =ifrude {"sup nerd."}else{"hello, friend!"};if letOk(x) ="123".parse::<i32>() {println!("{} double that and you get {}!", greeting, x *2);}Shown above are the three typical forms anif block comes in. First is the usual kind ofthing you’d see in many languages, with an optionalelse block. Second usesif as anexpression, which is only possible if all branches return the same type. Anif expression canbe used everywhere you’d expect. The third kind ofif block is anif let block, whichbehaves similarly to using amatch expression:
if letSome(x) =Some(123) {// code}else{// something else}matchSome(123) {Some(x) => {// code},_=> {// something else},}Each kind ofif expression can be mixed and matched as needed.
iftrue==false{println!("oh no");}else if"something"=="other thing"{println!("oh dear");}else if letSome(200) ="blarg".parse::<i32>().ok() {println!("uh oh");}else{println!("phew, nothing's broken");}Theif keyword is used in one other place in Rust, namely as a part of pattern matchingitself, allowing patterns such asSome(x) if x > 200 to be used.
For more information onif expressions, see theRust book or theReference.