Model skeleton
- Rust course
- Intermediate
- Lesson 107/115
- 6 min
Set up the model by adding serde derive to the Post struct.
Blog project: the model
In this project we'll write a small tool that reads blog posts from a file, filters them and can be queried from the command line. In a real project posts are read from JSON with serde and commands parsed with clap; in the exercises we'll build the same steps with the standard library. The first step is the data model:
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Yazi {
id: u32,
konu: String,
yazar: String,
etiketler: Vec<String>,
yayinda: bool,
}Clone is useful when filter results must be returned as independent copies.
Creating an instance
A short helper can be used for tests and sample data:
let y = Yazi {
id: 1,
konu: String::from("Rust ile başlangıç"),
yazar: String::from("ece"),
etiketler: vec![String::from("rust")],
yayinda: true,
};
println!("{:?}", y);The {:?} output shows the fields in declaration order; it's the fastest way to check the model while debugging.
Practice Post model
Define the Yazi struct above with #[derive(Debug, Clone)]. Create a post with id: 1, "Rust ile başlangıç", "ece", ["rust"], true and print it with {:?}.
Starter code
fn main() {
// buraya yaz
}Sample solution
#[derive(Debug, Clone)]
struct Yazi {
id: u32,
konu: String,
yazar: String,
etiketler: Vec<String>,
yayinda: bool,
}
fn main() {
let y = Yazi {
id: 1,
konu: String::from("Rust ile başlangıç"),
yazar: String::from("ece"),
etiketler: vec![String::from("rust")],
yayinda: true,
};
println!("{:?}", y);
}Expected output
Yazi { id: 1, konu: "Rust ile başlangıç", yazar: "ece", etiketler: ["rust"], yayinda: true }
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why was <code>Vec<String></code> chosen for the tags?
- A post can have zero or many tags and should own its data Correct answer
- Tags are numbers
- A String can't hold one tag
- serde only reads Vec
Explanation: With Vec<&str>, the post would depend on the text living somewhere else.
2 Tags field
struct Yazi {
id: u32,
etiketler: ____,
}
struct Yazi {
id: u32,
etiketler: Vec<String>,
}
Explanation: Vec<String> is used for many owned texts.
3 Field and type
| Term | Meaning |
|---|---|
id |
u32 |
konu |
String |
etiketler |
Vec<String> |
yayinda |
bool |