Rust 101: Conditional Statements
In the previous article, we discussed about collections in rust. Now let’s dive into Conditional statements.
TL;DR
- Relational operators
- If
- If-Else
- Switch
First, let’s start off by creating a new project called “Conditions” using the following command
cargo new Conditions --bin
Relational operators
Relational operators in rust are similar to most of the other programming languages out there.
Here is the list of relational operators
- a<b — ‘a’ is greater than ‘b’
- a>b — ‘a’ is less than ‘b’
- a>=b — ‘a’ is greater than or equal to ‘b’
- a<=b — ‘a’ is less than or equal to ‘b’
- a==b — ‘a’ is equal to ‘b’
- a!=b — ‘a’ is not equal to ‘b’
- || — OR
- && — AND
If statements
The easiest and the most basic of the conditional statements in rust. It is syntactically very similar to other languages
Here is the syntax
if <condition> {
<statements>}
Sample code
If-Else statement
If-Else helps in checking multiple conditions. It is syntactically very similar to other languages.
Here is the syntax
if <condition> {
<statements>}
else if <condition>{
<statements>
}
else{
<statements>
}
Sample code
Shorthand notation
Rust allows you to store the result of an If-Else statement in a variable
Here is the syntax
let <var name> = if <condition>{ true };else{ false }
Sample code
The output of this code will be
Is Of Age: true
Switch statement
Switch in rust is called match. Match statements are used quite often in rust and 3rd party libraries. We have used “Match” before while accessing value in a HashMaps as discussed in the previous article on “Collections”. We will be seeing more of match in the upcoming articles as well.
Here is the syntax
match <var name>{
<value1> => <statement>,
<value2> | <value2> => <statement>, //OR operator
_ => <statement>,
}
- “_” is used as the “default” condition for the switch statement.
- OR condition can be used instead of a value with “|”. Note it is a “|” and not “||” like the once used in If statements.
- “…” can be used to represent range.
Sample code
In the next article, we will discuss about functions.
link to the next article
Link to the previous article