Skip to content
Related Articles

Related Articles

Improve Article
Rust – If-else Statement
  • Last Updated : 15 Mar, 2021

Branching with if-else in rust also is similar to other languages. Just the difference is the way of writing(syntax). Here the condition doesn’t need to be surrounded by parenthesis. Decision-making structure is an important part of life. Similarly, in programming also there are situations where you have to decide(make decisions) that for the specific conditions which code should be executed. For this, we use the if-else. 

Decision-making statements in programming languages decide the direction of the flow of program execution.

Mainly there are 3 types that are used more often are explained in this article.

They are:

  1. if statement
  2. if-else statement
  3. else-if ladder statement

If Statement

Here only 1 condition is there and if that condition is true then a block of code inside the if statement will be executed.



Syntax: 

if boolean_expression {
   // statement(s) will execute if the boolean expression is true
}

Example: To check if the number is negative or positive.

Rust




fn main(){
   let num = -5;
   if num < 0 {
      println!("number is negative") ;
   }
}

Output:

number is negative

If-Else Statement

Here also there is only 1 condition but the difference here is that there is another block of code that is executed when the if the condition is false and suppose that the condition is true then the block of code inside if is executed and else part is ignored completely.

Syntax: 

if boolean_expression {
   // if the boolean expression is true statement(s) will execute
} else {
   //if the boolean expression is false statement(s) will execute 
}

Example: To check which number is bigger

Rust




fn main(){
   let num = 3;
  let num1=-3
   if num > num1 {
      println!("1st number is bigger") ;
   }
  else {
    println!("2nd number is bigger") ;
  }
}

Output:

1st number is bigger

Else-If Ladder Statement

In this, there is more than 1 condition. In fact, there can be many and after that, there is else now suppose any of the conditions does not satisfy then all are ignored and block of code inside else part will be executed. But suppose if some condition is satisfied then the block of code in that part will be executed and rest will be ignored.

Syntax:

if boolean_expression1 {
   //statements if the expression1 evaluates to true
} else if boolean_expression2 {
   //statements if the expression2 evaluates to true
} else {
   //statements if both expression1 and expression2 result to false
}

Example: To check if the number is negative, positive or zero

Rust




fn main() {
   let num = 0 ;
   if num > 0 {
      println!("num is positive");
   } else if num < 0 {
      println!("num is negative");
   } else {
      println!("num is neither positive nor negative") ;
   }
}

Output:

num is neither positive nor negative



My Personal Notes arrow_drop_up
Recommended Articles
Page :