Rust
Adding
Write a function that appends a new task to Vec<Todo>.
Adding
Let's gather the tasks in a Liste struct. To give new tasks increasing ids, we also keep the last id used:
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
}
}
ekle takes &mut self because it changes the list, and returns the new task's id.
Constructor
To make creating an empty list easy, a new associated function can be written:
impl Liste {
fn new() -> Self {
Self { gorevler: Vec::new(), sonraki_id: 0 }
}
}
let mut liste = Liste::new();
let id = liste.ekle("Süt al"); // 1
Since the list will be changed, the variable is declared with let mut.
Exercise Add tasks
Write fn new() -> Self and fn ekle(&mut self, metin: &str) -> u32 for Liste. Add the tasks "Süt al" and "Kod yaz"; print the number of tasks in the list and the last id added, separated by a space.
Show example solution
struct Gorev {
id: u32,
metin: String,
bitti: bool,
}
struct Liste {
gorevler: Vec<Gorev>,
sonraki_id: u32,
}
impl Liste {
fn new() -> Self {
Self {
gorevler: Vec::new(),
sonraki_id: 0,
}
}
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 main() {
let mut liste = Liste::new();
liste.ekle("Süt al");
let son = liste.ekle("Kod yaz");
println!("{} {}", liste.gorevler.len(), son);
}
Test yourself
-
Why does <code>ekle</code> take <code>metin: &str</code> and call <code>to_string()</code> inside?
- to_string is mandatory
- So the caller can pass either a literal or a String, while the task owns its own copy
- &str prints faster
- A String parameter can't be taken
Show answer
So the caller can pass either a literal or a String, while the task owns its own copy — A flexible &str in the parameter, an owned String when storing: a common Rust pattern.
-
Push to the vector
self.gorevler.____(Gorev {
id: self.sonraki_id,
metin: metin.to_string(),
bitti: false,
});
Show answer
self.gorevler.push(Gorev {
id: self.sonraki_id,
metin: metin.to_string(),
bitti: false,
});
-
Piece and role
- Vec<Gorev>
- Holds the tasks
- sonraki_id
- Last id
- &mut self
- Changes the list
- Liste::new()
- Empty list
Next lesson: Listing