The condition MUST evaluate to a boolean.
if num == 5 { msg = "five"; } else if num == 4 { msg = "four"; } else { msg = "other"; }
You can also assign a variable to the result of the condition. Note: you must use tail expressions in this case.
let msg = if num == 5 { "five" } else if num == 4 { "four" } else { "other" };
Ternaries in Rust can be written like so:
num = if a { b } else { c };
There is also an unconditional loop:
loop { println!("Hello, world!"); }
You can even break out of a deep-nested loop with break
and naming.
'bob: loop { 'joe: loop { break 'bob; } }
A similar thing can be done with continue
.
While loops are also very similar to other languages, but there are no do
blocks.
while dizzy() { // do stuff }
Rust also has ways to iterate through an iterator. It can even take a pattern or work through a range.
// iterate in order for num in [7,8,9].iter() { println!("{}", num); } // iterate with a pattern let array = [(1,2), (3,4)]; for (x,y) in array.iter() { println!("{} {}", x, y); } // For ranges -> note the end here is exclusive for num in 0..50 { println!("{}", num); } // This range includes the end for num in 0..=50 { if num % 2 == 0 { println!("{}", num); } }
"Here be dragons" - there can be 6 types of strings in Rust, but there are generally always two types:
str
which we will generally get as a borrow string slice &str
.String
where the data can be modified.You will often create a string by using the to_string()
or String::from()
methods on a string slice.
A borrowed string slice is essentially a pointer to a string slice and a length.
A String
is a pointer to a string with a length and capacity.
Strings cannot be indexed by a number.
If you need to index things like graphemes, be sure to check out the packages out there.