Listing
- Rust course
- Beginner
- Lesson 91/115
- 6 min
Print tasks with a for loop.
Listing
Printing the tasks only needs reading, so &self is enough. We loop over the vector by borrowing it with &self.gorevler:
fn listele(&self) {
for g in &self.gorevler {
let isaret = if g.bitti { "x" } else { " " };
println!("[{}] {}: {}", isaret, g.id, g.metin);
}
}Had we written for g in self.gorevler, we would try to move the vector; since a field behind &self can't be moved, we'd get a compile error.
Empty list message
A descriptive message for an empty list is a good user experience:
fn listele(&self) {
if self.gorevler.is_empty() {
println!("Görev yok.");
return;
}
for g in &self.gorevler {
// ...
}
}An early return keeps the main logic unindented.
Practice List the tasks
Write the methods ekle and listele for Liste. Add "Süt al" and "Kod yaz" and call listele().
Starter code
struct Gorev {
id: u32,
metin: String,
bitti: bool,
}
struct Liste {
gorevler: Vec<Gorev>,
sonraki_id: u32,
}
fn main() {
// buraya yaz
}Sample solution
struct Gorev {
id: u32,
metin: String,
bitti: bool,
}
struct Liste {
gorevler: Vec<Gorev>,
sonraki_id: u32,
}
impl Liste {
fn ekle(&mut self, metin: &str) -> u32 {
self.sonraki_id += 1;
self.gorevler.push(Gorev {
id: self.sonraki_id,
metin: metin.to_string(),
bitti: false,
});
self.sonraki_id
}
fn listele(&self) {
for g in &self.gorevler {
let isaret = if g.bitti { "x" } else { " " };
println!("[{}] {}: {}", isaret, g.id, g.metin);
}
}
}
fn main() {
let mut liste = Liste {
gorevler: Vec::new(),
sonraki_id: 0,
};
liste.ekle("Süt al");
liste.ekle("Kod yaz");
liste.listele();
}Expected output
[ ] 1: Süt al [ ] 2: Kod yaz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>listele</code> print if the list is empty?
- Nothing; the loop never runs Correct answer
- It panics
- It prints "[]"
- It prints None
Explanation: A for loop over an empty vector runs zero times. To be user-friendly, a separate message can be shown with is_empty.
2 Loop by borrowing
for g in ____self.gorevler {
println!("{}", g.metin);
}
for g in &self.gorevler {
println!("{}", g.metin);
}
Explanation: &self.gorevler loops over the vector without moving it.
3 Loop and result
| Term | Meaning |
|---|---|
for g in &v |
Borrows |
for g in &mut v |
Loops while modifying |
for g in v |
Moves |
v.is_empty() |
Is it empty? |