Learning Rust Pt. 6

Sunday, February 19, 2023 | Permalink

Writing a condition is quite easy in Rust and follow simple and intuitive syntax and rule.

  1. No need to write the condition within bracket.
fn main() {
  let x = 4;
  
  if x % 2 == 0 {
    println!("{} is even.", x);
  }
}
  1. The expression must be evaluated to boolean value, otherwise, Rust will complain.
fn main() {
  let x = 4;
  
  if x {
    println!("{} is even.", x);
  }
}

As usual, we've the else with if.

fn main() {
  let x = 4;
  
  if x % 2 == 0 {
    println!("{} is even.", x);
  } else {
    println!("{} is odd.", x);
  }
}

Or you can even use else if in some specific scenario.

fn main() {
  let x = 4;
  
  if x > 0 {
    println!("{} is positive.", x);
  } else if x < 0 {
    println!("{} is negative.", x);
  } else {
    println!("{} must be zero.", x);
  }
}

Labels: