Rust
State with Vec
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.
Exercise 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().
Show example 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);
}
}
Test yourself
-
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
- Using a static variable
Show answer
Saving the state to a file and reading it on startup — In the file I/O and serde lessons we'll store the notes as JSON.
-
Numbered lines
self.notlar.iter().____()
.map(|(i, n)| format!("{}. {}", i + 1, n))
Show answer
self.notlar.iter().enumerate()
.map(|(i, n)| format!("{}. {}", i + 1, n))
-
Expression and result
- args[2..].join(" ")
- "süt al"
- notlar.len()
- Number of notes
- (0, "a") → format
- "1. a"
- Defter::new()
- Empty notebook
Next lesson: Result and commands