State with Vec
- Rust course
- Intermediate
- Lesson 61/115
- 6 min
Hold application state with a Vec.
State with a Vec
Let's write a Defter type keeping the notes in memory in a Vec<String>. Numbers are shown to the user starting from 1:
struct Defter {
notlar: Vec<String>,
}
impl Defter {
fn ekle(&mut self, metin: String) {
self.notlar.push(metin);
}
fn liste(&self) -> Vec<String> {
self.notlar.iter().enumerate()
.map(|(i, n)| format!("{}. {}", i + 1, n))
.collect()
}
}liste returns the lines instead of printing them; this way the output is testable and reusable elsewhere.
Joining arguments
In the command not ekle süt al, the text is split across several arguments; it's joined into one text with join(" "):
let args = ["not", "ekle", "süt", "al"];
let metin = args[2..].join(" "); // "süt al"The slice [2..] gives all arguments after the command name.
Practice Add and list notes
Add the liste method to Defter. Build the text from the arguments ["not", "ekle", "süt", "al"] with join and add it, then add "kod yaz"; print the lines of liste().
Starter code
struct Defter {
notlar: Vec<String>,
}
impl Defter {
fn new() -> Self {
Self { notlar: Vec::new() }
}
fn ekle(&mut self, metin: String) {
self.notlar.push(metin);
}
}
fn main() {
// buraya yaz
}Sample solution
struct Defter {
notlar: Vec<String>,
}
impl Defter {
fn new() -> Self {
Self { notlar: Vec::new() }
}
fn ekle(&mut self, metin: String) {
self.notlar.push(metin);
}
}
impl Defter {
fn liste(&self) -> Vec<String> {
self.notlar
.iter()
.enumerate()
.map(|(i, n)| format!("{}. {}", i + 1, n))
.collect()
}
}
fn main() {
let mut d = Defter::new();
let args = ["not", "ekle", "süt", "al"];
d.ekle(args[2..].join(" "));
d.ekle(String::from("kod yaz"));
for s in d.liste() {
println!("{}", s);
}
}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 In a real CLI the notes vanish when the program exits. How is this solved?
- A HashMap instead of a Vec
- It can't be solved
- Saving the state to a file and reading it on startup Correct answer
- Using a static variable
Explanation: In the file I/O and serde lessons we'll store the notes as JSON.
2 Numbered lines
self.notlar.iter().____()
.map(|(i, n)| format!("{}. {}", i + 1, n))
self.notlar.iter().enumerate()
.map(|(i, n)| format!("{}. {}", i + 1, n))
Explanation: enumerate adds each note's position, starting from 0.
3 Expression and result
| Term | Meaning |
|---|---|
args[2..].join(" ") |
"süt al" |
notlar.len() |
Number of notes |
(0, "a") → format |
"1. a" |
Defter::new() |
Empty notebook |