Rust: Decision Making
Status: Courses Tags: Rust
if-else construct
-
if-elsein Rust is not a statement but an expression.- Statements do not return any value
- Expressions return value.
-
Hence
if elsein Rust return value which can be ignored or assigned to a variable -
Both
ifandelsebranches should return the same type of value. Because Rust does not allow multiple types to be stored in a variable. -
For example:
#![allow(unused)] fn main() { // Simple example if i < 10 { // the statement with semicolon hence the return value is () println!("Value is less than 10"); } else { println!("Value is more than 10"); } // complex example let result = if i < 10 { // the statement without semicolon is considered as return value 1 } else { // 0 is returned, and type is kept same 0 } }match expression
-
matchin Rust is a replacement toswitchandcasein C. -
For Example:
// Simple match usage // Returns an HTTP status fn req_status() -> u32 { 200 } fn main() { let status = req_status(); let result = match status { 200 => { println!("HTTP Success!"); }, 404 => println!("Page not found!"), other => println!("Reequest Failed, Status code {}!", other); } } -
matchstatement has to have branches for all the possible cases (match exhaustively). i.e in the Above case, we have to match against all the numbers until a maximum of u32. -
otheris used to catch all and store the value. -
_is used to catch all and ignore the value. -
matchis an expression so it returns a value. -
Each branch in
matchshould return the same type of value because Rust does not allow one variable to store multiple types.
-