Rust Notes: If Conditionals
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.
rust
// 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.
rust
// 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.
If Considerations
- The condition MUST evaluate to a boolean
- Semi-colons at the end of the branches are not required as they are considered tail-expressions.
- When an if block returns a value:
- A terminating semi-colon on the if block is required.
- All branches must return the same type.
Links
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