Um momento
0x30Lesson 4 of 6

Branch and loop over vectors

Use `if`, `match`, loops, and vectors.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • 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. Use iterator patterns and loops to transform and aggregate data clearly.

main.rs
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}
Output
25

Rust’s match enforces handling every case, which improves correctness. For loops over vectors are concise and type-safe.

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 C.

Exercise 1

Sum N numbers

+25 XP

Read a count and then that many integers (one per line). Print their sum.

  • Three values
  • Negative value
main.rs
Loading editor…

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…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: