I’m new to rust and decided to throw myself in the deep end. So I’m currently making a notes taking app in the terminal, and I want to save the notes in json format. But I keep getting this error:
error[E0277]: the trait bound `Note: Serialize` is not satisfied
--> srcmain.rs:92:35
|
92 | serde_json::to_writer(writer, notes)?;
| --------------------- ^^^^^ the trait `Serialize` is not implemented for `Note`, which is required by `Vec<Note>: Serialize`
| |
| required by a bound introduced by this call
|
= help: the following other types implement trait `Serialize`:
bool
char
isize
i8
i16
i32
i64
i128
and 131 others
= note: required for `Vec<Note>` to implement `Serialize`
These are my save and load functions:
fn save_notes(notes: &Vec<Note>) -> Result<(), std::io::Error> {
let file = File::create("notes.json")?;
let writer = BufWriter::new(file);
serde_json::to_writer(writer, notes)?;
Ok(())
}
fn load_notes() -> Result<Vec<Note>, std::io::Error> {
let file = File::open("notes.json");
match file {
Ok(file) => {
let reader = BufReader::new(file);
let notes = serde_json::from_reader(reader)?;
Ok(notes)
}
Err(_) => Ok(Vec::new()),
}
}
This is my main fn and libs:
use std::fs::File;
use std::io::{self, Write, Read, BufWriter, BufReader};
use uuid::Uuid;
use serde::{Serialize, Deserialize};
use serde_json;
struct Note {
content: String,
uuid: Uuid,
}
fn main() {
println!("Welcome to Ter Notes! A terminal based note taking application.");
let mut notes: Vec<Note> = load_notes().unwrap_or_else(|_| Vec::new());
println!("Commands: n 1: Take note n 2: Print notes n 3: Delete note n 4: Help n 5: Exit ");
loop {
println!("Enter command: ");
let mut command = String::new();
io::stdin()
.read_line(&mut command)
.expect("Failed to read line");
match command.trim() {
"1" => {
take_note(&mut notes);
save_notes(¬es).expect("Failed to save notes");
}
"2" => print_notes(¬es),
"3" => {
remove_note(&mut notes);
save_notes(¬es).expect("Failed to save notes");
}
"4" => println!("Commands: n 1: Take note n 2: Print notes n 3: Delete note n 4: Help n 5: Exit "),
"5" => break,
_ => println!("Invalid command."),
}
}
}
My Cargo.toml:
[dependencies]
uuid = { version = "1.9.0", features = [
"v4",
"fast-rng",
"macro-diagnostics",
] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_derive = "1.0"
I have tried debugging it using ai, but that went horribly wrong.
I have added #[derive(Serialize, Deserialize)]
to my Note struct, I got the same error and a new one about uuid not able to serialize.
If you have any ideas on how to optimize my code and better ways to save my code, feel free to share.