• Course List
  • Introduction to Rust
  • Environment Setup
  • First Rust Application
  • Variables & Constants
  • Control Flow
  • if, else if, else, match
  • while, for loops
  • break & continue
  • Intermediate
  • Borrowing & Referencing
  • Structs (Structures)
  • Enums (Enumerations)
  • Collections
  • Vector Collection
  • HashMap Collection
  • Advanced Types
  • Memory Management
  • Smart Pointers
  • Multi-Threading
  • Concurrency

Rust Conditional Control (if, else if, else, match) Tutorial

In this Rust tutorial we learn how to control the flow of our Rust application with if, else if, else, and match conditional statements.

We also cover how to nest conditional statements inside other conditional statements as well as how to conditionally assign a value to a variable if the if let expression.

  • What is conditional control flow
  • The if conditional statement
  • How to evaluate multiple if conditions
  • The conditional else if ladder
  • The conditional fallback else statement
  • How to nest if, else if and else statements
  • The conditional match statement
  • Conditional variable assignment (if let)
  • The Rust ternary operator
  • Summary: Points to remember

Rust allows us to control the flow of our program through specific expressions that evaluate conditions. Based on the result of these conditions, Rust will execute sections of specified code.

As an example, let’s consider a application with a dedicated area for members. Before a user can gain access to the member area, they need to provide the correct login credentials.

If they provide the correct credentials, they are allowed into the exclusive member area. Otherwise, they will be given the option to try again or reset their password if they have forgotten it.

Based on this logic, we can imagine that our code would look something like this.

Our actual code will not look exactly like the example above, but it serves to give you an example of what conditional control is.

We control the flow of our program with the following statements, in combination with relational comparison and logical operators.

We give an if statement a condition to evaluate. If the condition proves true, the compiler will execute the if statement’s code block.

If the condition proves false, the compiler will move on to code below the if statement’s code block.

An if statement is written with the keyword if , followed by the condition(s) we want it to evaluate.

Then, we specify a code block with open and close curly braces. Inside the code block we write one or more expressions to be executed if the evaluation proves true.

Note that an if statement is not terminated with a semicolon. The closing curly brace will tell the compiler where the if statement ends.

In the example above, our variable a has a value less than 10, so the condition proves true. The compiler then prints the message inside the if statement’s code block.

When the compiler has finished executing the if statement, it will move on to any code after it. The same is true when our if statement proves false, the compiler will move on to the next piece of code outside and below the if statement.

In the example above, our if condition proves false. The compiler then moves on to the next section of code after the if statement.

We can evaluate more than one condition in an if statement with the help of the two logical operators && and ||.

Conditional AND is used to test if one condition and another proves true. Both conditions must prove true before the code will execute.

To evaluate multiple conditions with AND, we separate them with the && operator.

In the example above, both of our conditions prove true so the code inside the if code block executes.

The conditional OR is used to test if one condition or another proves true. Only one of the conditions must prove true before the code will execute.

To evaluate multiple conditions with OR, we separate them with the || operator.

In the example above, the first condition proves false, but the second condition proves true so the compiler is allowed to execute the code in the code block.

When we have multiple types of conditions that do not fit within a single if condition, we can write more if statements and combine them into an else if ladder.

The compiler will move to evaluate each if statement in the ladder when it’s done with previous one.

To write a conditional else if statement, we add another if statement below our first, separated by the else keyword.

In the example above, we add a secondary if statement at the end of the first, separated by the else keyword.

Note that an else if statement can only follow an if statement, it cannot stand on its own. The first conditional must always be an if.

We can have as many else if statements in a ladder as we need.

The else statement works as a catch-all fallback for anything that isn’t covered by an if statement or else if ladder.

Because it acts as a catch-all, the else statement doesn’t have a conditional block, only an execution code block.

In the example above, the else statement will execute any result other than number == 10. Because number is not 10, the compiler executes the else execution code block.

We can place if statements inside other if statements, a technique known as nesting. The compiler will perform the evaluations hierarchically, that’s to say, it will start out the outer if statement and move inwards.

To nest an if statement, we simply write it inside the execution code block of another if statement.

In the example above, our outer if statement condition proves true. The compiler then evaluates the inner if statement and executes its code block if its condition proves true.

Nested if statements are used when we want to evaluate conditions only if other conditions are true.

Note that if you find yourself nesting more than 3 levels deep, you should consider finding a different method. Perhaps a loop.

The match statement will check a single value against a list of values.

If you’re familiar with a languages in the C family, it would be similar to a switch statement, although the syntax is different.

Let’s take a look at the syntax before we explain.

There’s a lot going on here and it may seem confusing at first, so let’s take it step by step.

1. The match statement returns a value, so we can assign the whole statement to a variable to get the result.

2. Now we write the match statement itself. We use the keyword match, followed by the main value we are going to compare any other values to. Finally, we define a code block.

Note that the code block is terminated with a semicolon after the closing curly brace.

3. Inside the code block we will write the values that we want to try and match with the main value.

First, we specify the value we want to match, followed by a => operator. Then, inside another code block, we specify the execution statements if that value matches with the main value.

Each of these values are separated with a comma, and we can have as many as we need.

The final value to match is simply an underscore. The single, standalone, underscore in a match statement represents a catch-all situation if none of the values matched to the main value. Think of it as an else statement.

Now, let’s see a practical example of the match statement.

In the example above, we give a student a grade and store it in a variable. Then we check to see which grade score in the match statement the student’s score matches.

If the compiler finds a match on the left of the => operator, it will execute whatever statement is on the right of the => operator.

In this case, it matched to “B” on the left and so it printed the string “Great job, you got a B!”.

Note that we don’t use the result variable in the example above. This is simply because we don’t need to, the execution statement of the match already prints a message.

If we want to return an actual value, we specify the value instead of an action like println.

In the example above, we replaced the println!() statements with simple string values.

When the compiler finds a match on the left of the => operator, it will return the value on the right of the => into the result variable.

This time, the compiler matched to “A” on the left, so it stored the string “Excellent!” into the result variable.

We then used it in the println!() below the match statement.

We can conditionally assign a value to a variable with an if let expression. To do this, we simply write the if statement where the value should be in the variable initialization.

It’s important to note a few differences here to a normal if statement.

  • We must have both an if and else statement.
  • The execution expressions must provide a value to be assigned to the variable.
  • The individual statements in the code blocks are not terminated with a semicolon.
  • The if statement itself is terminated with a semicolon after the else closing curly brace.

In the example above, the if statement will prove true so the value assigned to the number variable is 1.

Let’s see another example.

As we know, a variable can only hold one type of value. If we try to assign different types of values to it through the if statement, the compiler will raise an error.

In the example above, the values we want to assign is of different types.

Eclipse will highlight the potential error for us before we compile. If we go ahead and compile anyway, the following error is raised.

Rust does not have a ternary operator anymore.

In many languages, such as C or Python we can write a shortened version of a simple if/else statement, known as the ternary operator.

Rust, removed the ternary operator back in 2012 . The language doesn’t support a ternary operator anymore.

  • We can control the flow of our application with conditional logic through if , else if , else and match statements.
  • The if and else if conditional statements must include a condition to evaluate.
  • The else statement is a catch-all fallback to if and else if and as such cannot have a condition.
  • We can nest if statements inside other if statements. The compiler will evaluate them hierarchically.
  • The match statement is similar to a switch statement in many other languages such as C,C++.
  • An if let expression places the if statement as the value of a variable declaration.
  • An if let expression is terminated with a semicolon after the code block closing brace.
  • Values inside the code blocks of an if let expression are not terminated with a semicolon.

DevsENV

Rust Programming

Conditional Logic in Rust - If-Else-Else-if Statements in RUST

  • if Expression In Rust
  • if..else Expressions In Rust
  • if..else if Expressions In Rust
  • Nested if..else In Rust

In system programming, you can use the if and if..else statements/evolution to run a block of code when a specific condition is met.

For example, we suggest a student can be assigned grades to a subject based on their in total score.

  • if the score is upon 80, then assign grade A
  • if the score is upon 70, then assign grade B
  • if the score is upon 60, then assign grade C

¶ Boolean Expression In Rust

At First we study about if..else evolutions, let’s speedily understand boolean evolutions.

A boolean evolution is an evolution (produces a value) which returns other true or false (boolean) as the output. For example-

Above Example, x > 5 is a boolean evolution that checks if the value of variable x is greater than 5 . as like 7 , the value of variable x is greater than 5 , and the condition variable is assigned true .

Here condition is true is seen as output.

¶ if Expression In Rust

An if evolution executes the code block only if the condition is true . The syntax of the if evolution in Rust is

If the situation evaluates to

  • true - the example code inside the if block is realized
  • false - the example code inside of the if block is not realized

Working of if expression in Rust (Condition is true)

**Output : **

Working of if expression in Rust (Condition is false)

¶ Example: if expression in Rust

In the example upon, we maked a variable number and prevented if its value is greater than 0. Notice the condition.

While the variable number is greater than 0 , the agreement evaluates to true . As a result, you see the code block inside of curly braces being evolved.

Suppose we alternative the number variable to a negative integer. Let’s we say -2 .

Now we see output will be:

This is the condition -2 > 0 appreciate to false and the body of if is scamper.

¶ if..else Expressions In Rust

The if evolution can once and again also include an optional else evolution. The else evolution is realized if the condition in if is false .

The syntax for the if..else evolution in Rust is :-

  • If agreement evaluates to true ,
  • the code block inside if is evolved
  • the code block inside else is scamper
  • If agreement evaluates to false,
  • the code block inside the if block is scamper
  • the code block inside the else block is evolved

Working of if..else expression in Rust ( if condition is true )

¶ Example: if..else expression In Rust

Below, the variable number has a value of -2 , so the agreement number > 0 evaluates to false . Here, the code block under of the else statement is evolved.

If you change the variable to a positive number. Let’s we say 10 .

Now we found The output of the program will be:

Above the example, the condition number > 0 evaluates to true. Here, the code block inside of the if statement is evolved.

¶ if..else if Expressions In Rust

You can appreciate multiple conditions by mix if and else in an else if evolution. An if..else if evolution is particularly helpful if we need to create more than two choices. The syntax for if with else if evolution looks like below:

1. If condition1 values to true

  • code block 1 is evolved
  • code block 2 and code block 3 is scamper

2. If condition2 values to true

  • code block 2 is evolved
  • code block 1 and code block 3 is scamper

3. If both condition1 & condition2 value to false

  • code block 3 is evolved
  • code block 1 and code block 2 is scamper

¶ Example: if..else if..else Conditional In Rust

In above example, you check if a number is positive, negative or zero. From number = -2 is less than 0 who content the condition: number < 0 , the else if block is evolved.

¶ Nested if..else In Rust

We can also use if..else evolution under the body of other if..else evolutions ,It is known as nested if..else in Rust Programming.

¶ Example: Nested if..else In Rust

Please see above example :-

The outer_condition number < 0 appreciates to true as the number variable is attributed to a value of -2 . this, the outer code block is appreciate.

The ostensible code block contains an inner_condition to check number == -2 , who is again true . this, the inner code block of the inner if evolution is realized.

The inner code block impress “ The current number is -2 ” to on the screen.

The inner else block is scamper because the inner_condition appreciated to true .

All Tutorials in this playlist

Getting Started with Rust Programming For Beginner's Guide

Getting Started with Rust Programming For Beginner's Guide

A Comprehensive Guide to Effective Comments In Rust Programming

A Comprehensive Guide to Effective Comments In Rust Programming

A Guide to Optimizing Print Output in Your Rust Programming

A Guide to Optimizing Print Output in Your Rust Programming

A Guide To Variables and Mutability In Rust Programming

A Guide To Variables and Mutability In Rust Programming

Exploring Rust Data Types: A Comprehensive Guide for Developers

Exploring Rust Data Types: A Comprehensive Guide for Developers

Rust Type Casting: A Comprehensive Guide for Efficient Programming

Rust Type Casting: A Comprehensive Guide for Efficient Programming

Rust Operators: A Comprehensive Guide to Efficient Code Handling

Rust Operators: A Comprehensive Guide to Efficient Code Handling

Conditional Logic in Rust - If-Else-Else-if Statements in RUST

A Comprehensive Guide to Rust for, while, and loop Constructs

Mastering Rust Data Types: A Comprehensive Guide for Developers

Mastering Rust Data Types: A Comprehensive Guide for Developers

Deep Dive into Rust Functions, Variable Scope, and Closures

Deep Dive into Rust Functions, Variable Scope, and Closures

Exploring the Core Features of Rust Standard Library

Exploring the Core Features of Rust Standard Library

Rust Error Troubleshooting Comprehensive Guide to Memory Management

Rust Error Troubleshooting Comprehensive Guide to Memory Management

Rust Modules: A Comprehensive Guide to Packages and Best Practices

Rust Modules: A Comprehensive Guide to Packages and Best Practices

Advanced Rust Topics: Dive Deeper into the Language's Capabilities

Advanced Rust Topics: Dive Deeper into the Language's Capabilities

Popular tutorials, vue js 3 - complete advance crud example with vuex, vue-validate, pagination, searching and everything, laravel eloquent vs db query builder [performance and other statistics], laravel role permission management system full example with source code, start wordpress plugin development with react js easily in just few steps, laravel membership management full project demo with source codes, numerical methods for engineers ebook & solution download - download pdf, connect your react app with websocket to get real time data, #ajax with laravel api and more - learn laravel beyond the limit, laravel ecommerce complete web application with admin panel, what is seeder in laravel and why we need it.

  • Artificial Intelligence (AI)
  • Bash Scripting

Bootstrap CSS

  • C Programming
  • Code Editor
  • Computer Engineering
  • Data Structure and Algorithm

Design Pattern in PHP

Design Patterns - Clean Code

  • Git Commands

Interview Prepration

Java Programming

Laravel PHP Framework

Online Business

  • Programming

React Native

Tailwind CSS

Uncategorized

Windows Operating system

  • Woocommerce

WordPress Development

  • C-sharp programming
  • Design pattern
  • Mathematics
  • Rust Programming Language
  • Windows terminal
  • WordPress Plugin Development

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, rust introduction.

  • Getting Started with Rust
  • Rust Hello World
  • Rust Comments
  • Rust Print Output
  • Rust Variables and Mutability

Rust Data Types

  • Rust Type Casting
  • Rust Operators

Rust Control Flow

Rust if...else.

  • Rust while Loop
  • Rust for Loop
  • Rust break and continue
  • Rust Struct

Rust Functions

  • Rust Function
  • Rust Variable Scope
  • Rust Closure

Rust Standard Library

  • Rust Stack and Heap
  • Rust Vector
  • Rust String
  • Rust HashMap
  • Rust HashSet
  • Rust Iterator

Rust Error and Memory

  • Rust Error Handling
  • Rust Unwrap and Expect
  • Rust Ownership
  • Rust References and Borrowing

Rust Modules and Packages

  • Rust Modules
  • Rust Crate and Package
  • Rust Cargo Package Manager

Rust Additional Topics

  • Rust Pattern Matching
  • Rust Generics
  • Rust Traits
  • Rust File Handling
  • Rust Macros
  • Rust Threads

Rust Tutorials

In computer programming, we use the if and if..else statements/expressions to run a block of code when a specific condition is met.

For example, a student can be assigned grades to a subject based on their overall score.

  • if the score is above 90, assign grade A
  • if the score is above 75, assign grade B
  • if the score is above 65, assign grade C
  • Boolean Expression

Before we learn about if..else expressions, let's quickly understand boolean expressions.

A boolean expression is an expression (produces a value) which returns either true or false (boolean) as the output. For example,

Here, x > 5 is a boolean expression that checks whether the value of variable x is greater than 5 . As 7 , the value of variable x is greater than 5 , the condition variable is assigned to true .

Hence, condition is true is seen as output.

  • Rust if Expression

An if expression executes the code block only if the condition is true . The syntax of the if expression in Rust is:

If the condition evaluates to

  • true - the code inside the if block is executed
  • false - the code inside of the if block is not executed

Working of if expression in Rust

Example: if expression

In the example above, we created a variable number and checked whether its value is greater than 0 . Notice the condition ,

Since the variable number is greater than 0 , the condition evaluates to true . As a result, we see the code block inside of curly braces being executed.

Suppose we change the number variable to a negative integer. Let's say -2 .

The output will be:

This is because the condition -2 > 0 evaluates to false and the body of if is skipped.

  • Rust if..else Expressions

The if expression can occasionally also include an optional else expression. The else expression is executed if the condition in if is false .

The syntax for the if..else expression in Rust is:

1. If condition evaluates to true ,

  • the code block inside if is executed
  • the code block inside else is skipped

2. If condition evaluates to false ,

  • the code block inside the if block is skipped
  • the code block inside the else block is executed

Working of if..else expression in Rust

Example: if..else expression

Here, the variable number has a value of -2 , so the condition number > 0 evaluates to false . Hence, the code block inside of the else statement is executed.

If we change the variable to a positive number. Let's say 10.

The output of the program will be:

Here, the condition number > 0 evaluates to true . Hence, the code block inside of the if statement is executed.

  • Rust if..else if Expressions

We can evaluate multiple conditions by combining if and else in an else if expression. An if..else if expression is particularly helpful if you need to make more than two choices. The syntax for if with else if expression looks like this:

1. If condition1 evaluates to true,

  • code block 1 is executed
  • code block 2 and code block 3 is skipped

2. If condition2 evaluates to true,

  • code block 2 is executed
  • code block 1 and code block 3 is skipped

3. If both condition1 and condition2 evaluate to false,

  • code block 3 is executed
  • code block 1 and code block 2 is skipped

Working of if..else if expression in Rust

Example: if..else if..else Conditional

In this example, we check whether a number is positive, negative or zero. Because number = -2 is less than 0 which satisfies the condition : number < 0 , the else if block is executed.

  • Nested if..else

You can use if..else expressions inside the body of other if..else expressions. It is known as nested if..else in Rust.

Example: Nested if..else

In this example,

  • The outer_condition number < 0 evaluates to true as the number variable is assigned to a value of -2 . Thus, the outer code block is evaluated.
  • The outer code block contains an inner_condition to check number == -2 , which is again true . Thus, the inner code block of the inner if expression is executed.
  • The inner code block prints " The current number is -2 " to the screen.
  • The inner else block is skipped because the inner_condition evaluated to true .

Table of Contents

  • Introduction

For now, this reference is a best-effort document. We strive for validity and completeness, but are not yet there. In the future, the docs and lang teams will work together to figure out how best to do this. Until then, this is a best-effort attempt. If you find something wrong or missing, file an issue or send in a pull request.

  • Light (default)

The Rust Reference

If and if let expressions, if expressions.

Syntax IfExpression :    if Expression except struct expression BlockExpression    ( else ( BlockExpression | IfExpression | IfLetExpression ) ) ?

An if expression is a conditional branch in program control. The form of an if expression is a condition expression, followed by a consequent block, any number of else if conditions and blocks, and an optional trailing else block. The condition expressions must have type bool . If a condition expression evaluates to true , the consequent block is executed and any subsequent else if or else block is skipped. If a condition expression evaluates to false , the consequent block is skipped and any subsequent else if condition is evaluated. If all if and else if conditions evaluate to false then any else block is executed. An if expression evaluates to the same value as the executed block, or () if no block is evaluated. An if expression must have the same type in all situations.

if let expressions

Syntax IfLetExpression :    if let Pattern = Expression except struct expression BlockExpression    ( else ( BlockExpression | IfExpression | IfLetExpression ) ) ?

An if let expression is semantically similar to an if expression but in place of a condition expression it expects the keyword let followed by a refutable pattern, an = and an expression. If the value of the expression on the right hand side of the = matches the pattern, the corresponding block will execute, otherwise flow proceeds to the following else block if it exists. Like if expressions, if let expressions have a value determined by the block that is evaluated.

if and if let expressions can be intermixed:

MarketSplash

Rust If-Else Statements: Key Concepts And Usage

The essentials of Rust if-else statements in this focused article. Designed for developers, we delve into the syntax, best practices, and practical applications of if-else logic in Rust programming.

Rust's if-else statements are a fundamental part of controlling the flow of your programs. They allow you to execute different code paths based on specific conditions. This article explores how these statements work in Rust, providing clear examples to enhance your understanding and application in real-world scenarios.

rust conditional variable assignment

Basic Structure Of If-Else Statements In Rust

Writing conditional expressions, implementing if-else logic in code, nested if-else statements, using if-else with match statements, frequently asked questions, if-else statement, evaluating conditions, using else if, omitting the else block.

The if-else statement in Rust is a control flow construct that allows you to execute different code paths based on a condition. At its core, the if statement evaluates a condition that returns a Boolean value ( true or false ).

In Rust, the condition in an if statement must be a Boolean expression. This is different from languages like C or Python, where non-Boolean expressions, such as integers or strings, can be used as conditions.

For multiple conditions, Rust allows the use of else if . This is useful for checking more than two possible outcomes.

In Rust, the else block is optional. If omitted and the if condition is false, the program simply skips the if block and continues.

Using Comparison Operators

Logical operators, combining conditions.

In Rust, conditional expressions are crucial for controlling the flow of a program. These expressions evaluate to a Boolean value ( true or false ), determining the path your program will take.

Commonly, conditional expressions involve comparison operators such as == (equality), != (inequality), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).

To combine multiple conditions, Rust uses logical operators like && (and), || (or), and ! (not). These operators allow for more complex conditional expressions.

You can combine multiple conditions in a single if statement for more complex logic. This approach is useful for checking various scenarios in one go.

Basic If-Else Implementation

Handling multiple conditions, conditional assignment.

In Rust, implementing if-else logic is straightforward. It involves evaluating conditions and executing code blocks based on these evaluations.

Start with a basic if-else structure. The if block executes when the condition is true, and the else block executes when the condition is false.

For more than two outcomes, use else if to handle multiple conditions . Each condition is checked in order until one is true.

Rust allows for conditional assignment using if-else. This is a concise way to assign values based on a condition.

Implementing Nested Logic

Avoiding deep nesting.

Nested if-else statements in Rust allow for more complex decision-making by placing one if-else block inside another. This is useful for checking multiple layers of conditions.

When implementing nested logic, the inner if-else block is placed within the outer block. This structure is ideal for evaluating conditions that depend on the outcome of a previous condition.

While nesting is powerful, deep nesting can make code hard to read and maintain. It's often better to use other constructs like match or separate functions for complex logic.

Sometimes, combining conditions using logical operators can be a simpler alternative to nesting.

Match As A Cleaner Alternative

Combining match and if-else, simplifying nested conditions.

In Rust, combining if-else statements with match constructs can lead to more concise and readable code. This approach is particularly useful when dealing with multiple conditions.

The match statement in Rust is similar to switch-case in other languages. It's a cleaner alternative to multiple if-else blocks, especially when dealing with enumerated types.

Sometimes, you might need to use if-else within a match arm to handle more complex conditions.

Using match with if-else can simplify nested conditions, making your code more organized and easier to follow.

Combining if-else with match statements in Rust provides a powerful tool for handling complex conditional logic in a structured and readable manner.

Is it mandatory to have an else block in an if-else statement?

No, the else block is optional in Rust. If the if condition is false and there is no else block, the program simply skips the if block.

What is the best practice for handling multiple conditions in Rust?

For multiple conditions, using match statements is often cleaner and more readable than multiple else if blocks, especially when working with enums.

How do I handle default cases in match statements?

Use the underscore _ as a catch-all pattern for default cases in match statements. This arm will match any value that hasn't been matched by the previous arms.

Let's see what you learned!

What is the correct syntax for an if-else statement in Rust?

Subscribe to our newsletter, subscribe to be notified of new content on marketsplash..

  • conditional-assignment 0.2.0
  • Docs.rs crate page
  • MIT OR Apache-2.0
  • Dependencies
  • 25% of the crate is documented
  • i686-pc-windows-msvc
  • i686-unknown-linux-gnu
  • x86_64-apple-darwin
  • x86_64-pc-windows-msvc
  • x86_64-unknown-linux-gnu
  • Feature flags
  • About docs.rs
  • Privacy policy
  • Rust website
  • Standard Library API Reference
  • Rust by Example
  • The Cargo Guide
  • Clippy Documentation

Crate conditional_assignment

Conditional-assignment.

GitHub Workflow Status (with branch)

This is a very simple, small crate to help make conditional assignments more ergonomic.

The goal is to make the below look a little better.

Minimum Supported Rust Version (MSRV)

According to cargo-msrv , the MSRV is 1.56.1 . Given how simple this crate is, I wouldn’t be surprised if the MSRV is lower, but I didn’t check. Try it!

Licensed under either of

  • Apache License, Version 2.0, ( LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0 )
  • MIT license ( LICENSE-MIT or http://opensource.org/licenses/MIT )

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

It's FOSS

  • Introduction to Rust Programming 🦀

Rust Basics 🦀

  • Rust Basics Series #1: Create and Run Your First Rust Program

Rust Basics Series #2: Using Variables and Constants in Rust Programs

  • Rust Basics Series #3: Data Types in Rust
  • Rust Basics Series #4: Arrays and Tuples in Rust
  • Rust Basics Series #5: Functions in the Rust Programming Language
  • Rust Basics Series #6: Conditional Statements
  • Rust Basics Series #7: Using Loops in Rust
  • Rust Basics Series #8: Write the Milestone Rust Program

Move ahead with your Rust learning and familiarize yourself with Rust programs' variables and constants.

In the first chapter of the series , I shared my thoughts on why Rust is an increasingly popular programming language. I also showed how to write Hello World program in Rust .

Let's continue this Rust journey. In this article, I shall introduce you to variables and constants in the Rust programming language.

On top of that, I will also cover a new programming concept called "shadowing".

The uniqueness of Rust's variables

A variable in the context of a programming language (like Rust) is known as an alias to the memory address in which some data is stored .

This is true for the Rust programming language too. But Rust has one unique "feature" compared to most other popular programming languages. Every variable that you declare is immutable by default . This means that once a value is assigned to the variable, it can not be changed.

This decision was made to ensure that, by default, you don't have to make special provisions like spin locks or mutexes to introduce multi-threading. Rust guarantees safe concurrency. Since all variables (by default) are immutable, you do not need to worry about a thread changing a value unknowingly.

This is not to say that variables in Rust are like constants because they are not. Variables can be explicitly defined to allow mutation. Such a variable is called a mutable variable .

Following is the syntax to declare a variable in Rust:

High-level overview of Rust's data types

In the previous article, you might have noticed that I mentioned that Rust is a strongly typed language. But to define a variable, you don't specify the data type, instead, you use a generic keyword let .

The Rust compiler can infer the data type of a variable based on the value assigned to it. But it can be done if you still wish to be explicit with data types and want to annotate the type. Following is the syntax:

Some of the common data types in the Rust programming language are as follows:

  • Integer type : i32 and u32 for signed and unsigned, 32-bit integers, respectively
  • Floating point type : f32 and f64 , 32-bit and 64-bit floating point numbers
  • Boolean type : bool
  • Character type : char

I will cover Rust's data types in more detail in the next article. For now, this should be sufficient.

Rust also enforces that a variable be initialized before the value stored in it is read.

If you declare a variable without an initial value and use it before assigning it some initial value, the Rust compiler will throw a compile time error .

Though errors are annoying. In this case, the Rust compiler is forcing you not to make one of the very common mistakes one makes when writing code: un-initialized variables.

Rust compiler's error messages

Let's write a few programs where you

  • Understand Rust's design by performing "normal" tasks, which are actually a major cause of memory-related issues
  • Read and understand the Rust compiler's error/warning messages

Testing variable immutability

Let us deliberately write a program that tries to modify a mutable variable and see what happens next.

Looks like a simple program so far until line 4. But on line 7, the variable b --an immutable variable--gets its value modified.

Notice the two methods of printing the values of variables in Rust. On line 4, I enclosed the variables between curly brackets so that their values will be printed. On line 8, I keep the brackets empty and provide the variables as arguments, C style. Both approaches are valid. (Except for modifying the immutable variable's value, everyting in this program is correct.)

Let's compile! You already know how to do that if you followed the previous chapter.

This perfectly demonstrates Rust's robust error checking and informative error messages. The first line reads out the error message that prevents the compilation of the above code:

It means that the Rust compiler noticed that I was trying to re-assign a new value to the variable b but the variable b is an immutable variable. So that is causing this error.

The compiler even identifies the exact line and column numbers where this error is found.

Under the line that says first assignment to `b` is the line that provides help. Since I am mutating the value of the immutable variable b , I am told to declare the variable b as a mutable variable using the mut keyword.

Playing with uninitialized variables

Now, let's look at what the Rust compiler does when an uninitialized variable's value is read.

Here, I have two immutable variables a and b and both are uninitialized at the time of declaration. The variable a gets a value assigned before its value is read. But the variable b 's value is read before it is assigned an initial value.

Let's compile and see the result.

Here, the Rust compiler throws a compile time error and a warning. The warning says that the variable b 's value is never being read.

But that's preposterous! The value of variable b is being accessed on line 7. But look closely; the warning is regarding line 8. This is confusing; let's temporarily skip this warning and move on to the error.

The error message reads that used binding `b` is possibly-uninitialized . Like in the previous example, the Rust compiler is pointing out that the error is caused by reading the value of the variable b on line 7. The reason why reading the value of the variable b is an error is that its value is uninitialized. In the Rust programming language, that is illegal. Hence the compile time error.

Example program: Swap numbers

Now that you are familiar with the common variable-related issues, let's look at a program that swaps the values of two variables.

Here, I have declared two variables, a and b . Both variables are mutable because I wish to change their values down the road. I assigned some random values. Initially, I print the values of these variables.

Then, on line 8, I create an immutable variable called temp and assign it the value stored in a . The reason why this variable is immutable is because temp 's value will not be changed.

To swap values, I assign the value of variable b to variable a and on the next line I assign the value of temp (which contains value of a ) to variable b . Now that the values are swapped, I print values of variables a and b .

When the above code is compiled and executed, I get the following output:

As you can see, the values are swapped. Perfect.

Using Unused variables

When you have declared some variables you intend to use down the line but have not used them yet, and compile your Rust code to check something, the Rust compiler will warn you about it.

The reason for this is obvious. Variables that will not be used take up unnecessary initialization time (CPU cycle) and memory space. If it will not be used, why have it in your program in the first place? Though, the compiler does optimize this away. But it still remains an issue in terms of readability in form of excess code.

But sometimes, you might be in a situation where creating a variable might not be in your hands. Say when a function returns more than one value and you only need a few values. In that case, you can't tell the library maintainer to adjust their function according to your needs.

So, in times like that, you can have a variable that begins with an underscore and the Rust compiler will no longer give you such warnings. And if you really do not need to even use the value stored in said unused variable, you can simply name it _ (underscore) and the Rust compiler will ignore it too!

The following program will not only not generate any output, but it will also not generate any warnings and/or error messages:

Arithmetic operations

Since math is math, Rust doesn't innovate on it. You can use all of the arithmetic operators you might have used in other programming languages like C, C++ and/or Java.

A complete list of all the operations in the Rust programming language, along with their meaning, can be found here .

Example Program: A Rusty thermometer

Following is a typical program that converts Fahrenheit to Celsius and vice a versa.

Not much is going on here... The Fahrenheit temperature is converted to Celsius and vice a versa for the temperature in Celsius.

As you can see here, since Rust does not allow automatic type casting, I had to introduce a decimal point to the whole numbers 32, 9 and 5. Other than that, this is similar to what you would do in C, C++ and/or Java.

As a learning exercise, try writing a program that finds out how many digits are in a given number.

With some programming knowledge, you might know what this means. A constant is a special type of variable whose value never changes . It stays constant .

In the Rust programming language, a constant is declared using the following syntax:

As you can see, the syntax to declare a constant is very similar to what we saw in declaring a variable in Rust. There are two differences though:

  • A constant name should be in SCREAMING_SNAKE_CASE . All uppercase characters and words separated by an undercase.
  • Annotating the data type of the constant is necessary .

Variables vs Constants

You might be wondering, since the variables are immutable by default, why would the language also include constants?

The following table should help alleviate your doubts. (If you are curious and want to better understand these differences, you can look at my blog which shows these differences in detail.)

A table that shows differences between Variables and Constants in the Rust programming language

Example program using constants: Calculate area of circle

Following is a straightforward program about constants in Rust. It calculates the area and the perimeter of a circle.

And upon running the code, the following output is produced:

Variable shadowing in Rust

If you are a C++ programmer, you already sort of know what I am referring to. When the programmer declares a new variable with the same name as an already declared variable, it is known as variable shadowing.

Unlike C++, Rust allows you to perform variable shadowing in the same scope too!

Let us take a look at how it works in Rust.

The :p inside curly brackets in the println statement is similar to using %p in C. It specifies that the value is in the format of a memory address (pointer).

I take 3 variables here. Variable a is immutable and is shadowed on line 4. Variable b is mutable and is also shadowed on line 9. Variable c is mutable but on line 14, only it's value is mutated. It is not shadowed.

Now, let's look at the output.

Looking at the output, you can see that not only the values of all three variables have changed, but the addresses of variables that were shadowed are are also different (check the last few hex characters).

The memory address for the variables a and b changed. This means that mutability, or lack thereof, of a variable is not a restriction when shadowing a variable.

This article covers variables and constants in the Rust programming language. Arithmetic operations are also covered.

As a recap:

  • Variables in Rust are immutable by default but mutability can be introduced.
  • Programmer needs to explicitly specify variable mutability.
  • Constants are always immutable no matter what and require type annotation.
  • Variable shadowing is declaring a new variable with the same name as an existing variable.

Awesome! Good going with Rust, I believe. In the next chapter, I discuss data types in Rust . Stay Tuned.

rust conditional variable assignment

Meanwhile, if you have any questions, please let me know.

On this page

Programming-Idioms

  • C++
  • Or search :

Idiom #252 Conditional assignment

Assign to the variable x the string value "a" if calling the function condition returns true , or the value "b" otherwise.

  • View revisions
  • Successive conditions
  • for else loop
  • Report a bug

Please choose a nickname before doing this

No security, no password. Other people might choose the same nickname.

Variable assignment

In this we will assign variable.

IMAGES

  1. Rust Course for Beginners

    rust conditional variable assignment

  2. Rust Programming Tutorial

    rust conditional variable assignment

  3. Rust Series Episode-07

    rust conditional variable assignment

  4. Rust Basics Series #6: Conditional Statements

    rust conditional variable assignment

  5. Rust Programming Complete Tutorial For Beginners|How To Declare Variable In Rust|Part:3

    rust conditional variable assignment

  6. Rust Programming Tutorial #5

    rust conditional variable assignment

VIDEO

  1. Rust

  2. If block in Rust

  3. Variables with mut keyword in Rust

  4. Let's Learn Rust: Fundamentals

  5. Conditional Statements

  6. Variable shadowing in Rust.....#coding #programming #rust #shadowing #javascript

COMMENTS

  1. Idiomatic way of assigning a value from an if else condition in Rust

    let mut s = "second".to_string(); if condition {. s = "first".to_string(); } It's shorter and doesn't generate a warning, but means s is being assigned twice, and means that "second".to_string() runs but is wasted if condition is true. If instead of simple string creation these were expensive operations (perhaps with side effects) this method ...

  2. If and if let expressions

    An if let expression is semantically similar to an if expression but in place of a condition operand it expects the keyword let followed by a pattern, an = and a scrutinee operand. If the value of the scrutinee matches the pattern, the corresponding block will execute. Otherwise, flow proceeds to the following else block if it exists.

  3. Rust Conditional Control (if, else if, else, match) Tutorial

    Conditional variable assignment (if let) The Rust ternary operator; Summary: Points to remember; What is conditional control flow Rust allows us to control the flow of our program through specific expressions that evaluate conditions. Based on the result of these conditions, Rust will execute sections of specified code.

  4. if/else

    Rust by Example (RBE) is a collection of runnable examples that illustrate various Rust concepts and standard libraries. ... Variable Bindings ... Unlike many of them, the boolean condition doesn't need to be surrounded by parentheses, and each condition is followed by a block. if-else conditionals are expressions, and, all branches must return ...

  5. Conditional Logic in Rust

    Above Example, x > 5 is a boolean evolution that checks if the value of variable x is greater than 5. as like 7, the value of variable x is greater than 5, and the condition variable is assigned true. Here condition is true is seen as output. ¶if Expression In Rust. An if evolution executes the code block only if the condition is true.

  6. Operator expressions

    The & (shared borrow) and &mut (mutable borrow) operators are unary prefix operators. When applied to a place expression, this expressions produces a reference (pointer) to the location that the value refers to. The memory location is also placed into a borrowed state for the duration of the reference. For a shared borrow ( & ), this implies ...

  7. Rust Conditional Statements: if, if-else, match

    In Rust, the if statement is used to execute a block of code when a given condition is true. The syntax for the if statement is as follows: if condition { // code to execute if the condition is true }

  8. Rust if...else (With Examples)

    Here, the variable number has a value of -2, so the condition number > 0 evaluates to false. Hence, the code block inside of the else statement is executed. If we change the variable to a positive number. Let's say 10. let number = 10; The output of the program will be: 10 is greater than 0. Here, the condition number > 0 evaluates to true.

  9. If and if let expressions

    If the value of the expression on the right hand side of the = matches the pattern, the corresponding block will execute, otherwise flow proceeds to the following else block if it exists. Like if expressions, if let expressions have a value determined by the block that is evaluated. let dish = ( "Ham", "Eggs" ); // this body will be skipped ...

  10. Conditional assignment

    Conditional assignment. - [Instructor] When we build out complex if else structures with multiple possible paths of execution, it can create the potential for problems. Consider the example code ...

  11. conditional

    Search Tricks. Prefix searches with a type followed by a colon (e.g., fn:) to restrict the search to a given type. Accepted types are: fn, mod, struct, enum, trait, type, macro, and const. Search functions by type signature (e.g., vec -> usize or * -> vec) Search multiple things at once by splitting your query with comma (e.g., str,u8 or String,struct:Vec,test)

  12. Rust If-Else Statements: Key Concepts And Usage

    Conditional Assignment; In Rust, implementing if-else logic is straightforward. It involves evaluating conditions and executing code blocks based on these evaluations. Basic If-Else Implementation. Start with a basic if-else structure. The if block executes when the condition is true, and the else block executes when the condition is false.

  13. conditional_assignment

    conditional-assignment. This is a very simple, small crate to help make conditional assignments more ergonomic. Intent. The goal is to make the below look a little better. ... Minimum Supported Rust Version (MSRV) According to cargo-msrv, the MSRV is 1.56.1. Given how simple this crate is, I wouldn't be surprised if the MSRV is lower, but I ...

  14. Condvar in std::sync

    A Condition Variable. Condition variables represent the ability to block a thread such that it consumes no CPU time while waiting for an event to occur. Condition variables are typically associated with a boolean predicate (a condition) and a mutex. The predicate is always verified inside of the mutex before determining that a thread must block.

  15. Rust Basics Series #2: Using Variables and Constants

    Following is the syntax: let variable_name: data_type = value; Some of the common data types in the Rust programming language are as follows: Integer type: i32 and u32 for signed and unsigned, 32-bit integers, respectively. Floating point type: f32 and f64, 32-bit and 64-bit floating point numbers. Boolean type: bool.

  16. Conditional assignment, in Rust

    Idiom #252 Conditional assignment. Assign to the variable x the string value "a" if calling the function condition returns true, or the value "b" otherwise. Rust. Ada.

  17. Variable assignment • Rust tutorial

    Variable assignment. In this we will assign variable. src/02-variables/main.rs. fn main {let age = 34; // by default variables are immutable println! ... let c: u8 = a + b; // rust compiler is smart enough to convert previous // assignments data types type_of (& c); const PI: f64 = 3.14159; // mut keyword is not allowed with const

  18. Variables

    Variables. A variable is a component of a stack frame, either a named function parameter, an anonymous temporary, or a named local variable.. A local variable (or stack-local allocation) holds a value directly, allocated within the stack's memory. The value is a part of the stack frame. Local variables are immutable unless declared otherwise. For example: let mut x = ....

  19. rust

    Instead of declaring an uninitialised variable like this. let var; if condition { var = value1; } else { var = value2; } you could directly initialise the variable with the alternative. let var = if condition { value1 } else { value2 }; Your variable does not even need the mut keyword (except if you want to mutate it afterwards).