Home » Rust if_in_a_let Statement

Rust if_in_a_let Statement

by Online Tutorials Library

Using “if in a let” statement

An ‘if’ expression is used on the right hand side of the let statement and the value of ‘if’ expression is assigned to the ‘let’ statement.

Syntax of ‘if in a let’

In the above syntax, if the condition is true then the value of ‘if’ expression is assigned to the variable and if the condition is false then the value of ‘else’ is assigned to the variable.

Rust if in a let statement

Example 1

Let’s see a simple example.

Output:

value of a is: 1  

In this example, condition is true. Therefore, ‘a’ variable bounds to the value of ‘if’ expression. Now, a consist 1 value.

Let’s see a another simple example.

Output:

Some errors occurred:E0308  

In this example, ‘if’ block evaluates to an integer value while ‘else’ block evaluates to a string value. Therefore, this program throws an error as both the blocks contains the value of different type.


Next TopicRust Loop

You may also like