Task model
- Rust course
- Beginner
- Lesson 89/115
- 6 min
Define the Todo struct and its fields.
Todo list: the model
In this project we'll write a small todo list that runs from the command line: adding tasks, listing, marking as done and reading commands. The first step is modelling the data. Every task has an id, a text and a done state:
struct Gorev {
id: u32,
metin: String,
bitti: bool,
}We chose String for metin because the task should own its text; if we held a &str, the text would have to live somewhere else.
Showing a task
Let a method decide how the task looks on screen. Finished tasks will be shown with [x], the others with [ ]:
impl Gorev {
fn goster(&self) -> String {
let isaret = if self.bitti { "x" } else { " " };
format!("[{}] {}: {}", isaret, self.id, self.metin)
}
}Since the method returns a String, printing, testing or saving the result to a file can all use the same code.
Practice First task
Add the method fn goster(&self) -> String to the Gorev struct. Create the task with id: 1, metin: "Süt al" and bitti: false, and print the result of goster().
Starter code
struct Gorev {
id: u32,
metin: String,
bitti: bool,
}
fn main() {
// buraya yaz
}Sample solution
struct Gorev {
id: u32,
metin: String,
bitti: bool,
}
impl Gorev {
fn goster(&self) -> String {
let isaret = if self.bitti { "x" } else { " " };
format!("[{}] {}: {}", isaret, self.id, self.metin)
}
}
fn main() {
let g = Gorev {
id: 1,
metin: String::from("Süt al"),
bitti: false,
};
println!("{}", g.goster());
}Expected output
[ ] 1: Süt al
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which type best fits a task's done state?
- u8
- Option<String>
- bool Correct answer
- String
Explanation: For two-state information (done/not done), bool is both clear and safe.
2 Pick the mark
let isaret = ____ self.bitti { "x" } else { " " };
let isaret = if self.bitti { "x" } else { " " };
Explanation: In Rust if is an expression; it can produce a value and be assigned to a variable.
3 Field and type
| Term | Meaning |
|---|---|
id |
u32 |
metin |
String |
bitti |
bool |
goster() |
-> String |