Control Flow in Rust
# Control Flow
control flow is great in rust
Rust doesn’t like type coersion the condition must resolve to a boolean
chaining condition else if finish with else
|
|
statements don’t return values expressions do. This means we change the above code to this
|
|
note:
- there are no semicolons after the branch vals, returns vals from blocks
- can’t use return for this purpose, return only applies to function bodies
- all blocks return the same type
- semicolon at the end of the if expression, especially when you return things from it.
No ternary operators
in rust since if is an expression you can do this
|
|
nested version is still readable (unlike ternary operators)
|
|
# Unconditional Loop
loops with no conditions.
# breaks
even these must end at some point so the break statement ends it.
|
|
! what if you want to break out of a nested loop?
|
|
annotate the loop you want to break out of. annotations have use a backtick at the beginning as the identifier. `bob then tell break which code you want to break out of.
# Continue is similar
|
|
by itself it continues the innermost loop unless you give it a label.
# while loops
|
|
while loops are mostly just syntactic sugar for putting a negated break condition at the top of an unconditional loop.
1 2 3 4 5 6 7
loop{ if !dizzy() { break } //do stuff } there is also no *do while* in rust but can be achieved by moving the break condition to the bottom of the loop. ```rust loop {
>//do stuff
>if !dizzy() { break }
}
# For loop
rusts for loop iterates over any iterable value compound and collection types will have a few different ways to get the iteration value from.
the iterator you use determines which items are returned and the order they are returned in
|
|
iter - iterates over all items in collection in order and randomly if collection is unordered.
for functional programming you can stack methods like map filter and fold and they will be lazily evaluated.
the for loop can take a pattern to destructure the items it revieves and bind the inside parts to variables just like the let statement, only in this case the variables are local to the body of the for loop.
|
|
functional for loop using iterators is often faster than for loops. iterator adapters are available. it can take actions on values as they pass through it.
|
|
map takes ownership, filter takes a reference.
! Always check the documentation !
Always end chain of iterator adapter with an iterator consumer! like .for_each
|
|
Turbofish
|
|
goes between the method name and the argument
|
|
|
|
# Collect
collect will gather all the items and put them into a new collection. Collect doesn’t know which collection type you would like. you need to tell it with <> after the vec.
you can also use underscore, because collect only needs to know the type of the container, it already knows the type of item. helpful for large item types.
|
|
you can also use a turbo fish at the collect section.
|
|