Branch and loop over vectors
Use `if`, `match`, loops, and vectors.
- Process a list of numbers and compute a result.
Rust has familiar control flow (if, else, while, for) plus match for exhaustive branching. Vec<T> is a growable array type.
1fn main() {
2 let scores = vec![8, 7, 10];
3 let mut total = 0;
4 for score in scores {
5 total += score;
6 }
7 println!("{}", total);
8}25
Rust’s match enforces handling every case, which improves correctness. For loops over vectors are concise and type-safe.
Try it
Up to 15 XPChoose the right control-flow tool
Sort each coding task by the Rust control-flow form that fits it best.
“Run one branch based on `score > 70`”
“Handle each enum variant and require all cases”
“Sum every item in a vector”
“Convert status code 200/404/500 to messages”
Key takeaways
Process a list of numbers and compute a result.
Rust uses types and ownership rules to prevent common bugs.
Small experiments build intuition quickly.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Rust
These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.
Sum N numbers
Read a count and then that many integers (one per line). Print their sum.
- Three values
- Negative value
Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…