published: 13th of February 2022
The if conditional block in Rust behaves similarly to other languages. In Rust, if blocks act as an expression and the resulting branch can be assigned to a variable.
// Example if block.
if "stuff" == "things" {
println!("equal") // Considered a tail-expression so semi-colon not required.
} else if 42 < 69 {
println!("the answer")
} else {
println!("lol")
} // terminating semi-colon optional when not returning an expression.
The resulting expression of an if branch can be assigned to a variable with the let keyword.
// Assign resulting expression to `the_answer` variable.
let the_answer = if 42 > 69 {
"the answer" // Considered a tail-expression so semi-colon not required.
} else {
"lol"
}; // terminating semi-colon is required when returning an expression.
https://www.manning.com/books/rust-in-action
https://www.udemy.com/course/ultimate-rust-crash-course/
https://doc.rust-lang.org/std/keyword.if.html
https://doc.rust-lang.org/book/ch03-05-control-flow.html#if-expressions