Rust Programming : Control Flow ( Section-1 )

Control Flow

Deciding whether or no to run some code depending on if a condition its true and deciding to run some code repeatdly while a condition is true are basic building blocks in most programming languages. The most common constructs that let us control the flow of executionof Rust code are if expressions and loops.


  • If Expressions
An if expression allows us to branch our code depending on conditions. We provide a condition and then state, "If this condition is met, run this block of code. If the condition is not met, do not run this block of code".

Look at this code for example :

fn main() {

let number = 3;
if number < 5 {

println!("The values of number is {} ", number);

} else {

println!("More than or equal with 5");

}

}

All if expressions start with keyword if, which is followed by a condition. In this case, the condition checks whether variable number has a value less than 5. The block of code we want to execute if the condition is true is placed immediately after the condition inside curly brackets. Blocks of code associated with the expressions in if expressions are sometimes called arms.

It's also worth noting that the condition in this code must be a bool. If the condition isn't bool, we'll get an error. Try this code for example :

fn main() {

let number = 3;

if number {
println!("The values if number is {}", number);
}

}

The error indicated that Rust expected a bool but got an integer. Unlike languages such as Ruby and Javascript, Rust will not automatically try to convert non-Boolean types to a Boolean. We must explicit and always provide if with a Boolean as its condition. If we want the if code block to run only when a number is not equal to 0.

In additional, we can have multiple conditions by combining if and else in an else if expression. For example :

fn main() {
let number = 6;

if number % 4 == 0 {
println!("The number is divisible by 4");
} else if number % 3 == 0 {
println!("The number is divisible by 3");
}
else if number % 2 == 0 {
println!("The number is divisible by 2");
}
}

This program has four possible paths it can take. When this program executes, it checks each if  expression in turn and executes the first body for which the condition hold true. Using too many else if expressions can clutter our code, so if we have more than one, we might want refactor our code. Later we'll discuss how to refactor our code with macth.


Ahmad Istakim

Alumni dari jurusan Manajemen Informatika di Universitas Sains Al-Qur'an (UNSIQ ) Wonosobo. Tertarik dalam bidang pendidikan, teknologi komputasi dan disiplin ilmu keislaman ( Tafsir, Hadits, Arudl, Nahwu-Sharaf, Fiqh maupun Aqidah ) - https://s.id/blog-islamQ. Pernah juga mengenyam pendidikan di beberapa pesantren yang ada di Kab. Wonosobo dan Kab. Purworejo

Posting Komentar

Lebih baru Lebih lama