Home » Rust if Statement

‘If’ statement

The ‘if’ statement determines whether the condition is true or not. If condition is true then the ‘if’ block is executed otherwise, control skips the ‘if’ block.

Different ways to represent ‘if’ block:

  • if block
  • if-else block
  • if else-if ladder
  • nested if

Syntax of ‘if’:

In the above syntax, if the condition is true then the block statements are executed otherwise it skips the block.

Flow Chart of “if statement”

Rust If statement

For Example:

Let’s see a simple example of ‘if’ statement.

Output:

a is equal to 1  

In this example, value of a is equal to 1. Therefore, condition given in ‘if’ is true and the string passed as a parameter to the println! is displayed on the console.


“if-else”

If the condition is true then ‘if’ block is executed and the statements inside the ‘else’ block are skipped. If the condition is false then ‘else’ block is executed and the statements inside the ‘if’ block are skipped.

Syntax of “if-else”

Flow Chart of “if-else”

Rust If statement

Let’s see a simple example of ‘if-else’ statement.

Output:

a is smaller than b  

In this example, value of a is equal to 3 and value of a is less than the value of b. Therefore, else block is executed and prints “a is smaller than b” on the screen.


else-if

When you want to check the multiple conditions, then ‘else-if’ statement is used.

Syntax of else-if

In the above syntax, Rust executes the block for the first true condition and once it finds the first true condition then it will not execute the rest of the blocks.

Flow Chart of “else if”

Rust If statement

Let’s see a simple example of else-if statement

Output:

number is less than 0  

In this example, value of num is equal to -5 and num is less than 0. Therefore, else if block is executed.


Nested if-else

When an if-else statement is present inside the body of another if or else block then it is known as nested if-else.

Syntax of Nested if-else

Let’s see a simple example of nested if-else

Output:

a is less than b  

In this example, value of a is not equal to b. So, control goes inside the ‘if’ block and the value of a is less than b. Therefore, ‘else’ block is executed which is present inside the ‘if’ block.


Next TopicRust if in a let

You may also like