Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created May 22, 2018 01:12
Show Gist options
  • Save rust-play/69da9672eac1ed004b3b1917f1175c19 to your computer and use it in GitHub Desktop.
Save rust-play/69da9672eac1ed004b3b1917f1175c19 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::collections::BTreeMap;
use std::io::{self, Write};
pub struct Todo {
name: String,
checked: bool,
priority: i32,
}
impl Todo {
pub fn write<W: Write>(&self, w: &mut W) {
write!(w, "{}:\n", self.name);
write!(w, "Checked: {}\n", self.checked);
write!(w, "Priority: {}\n", self.priority);
write!(w, "\n");
}
pub fn print(&self) {
self.write(&mut io::stdout());
}
}
#[derive(Default)]
pub struct TodoList {
list: BTreeMap<i32, Vec<Todo>>,
}
impl TodoList {
pub fn new() -> TodoList {
TodoList {
list: BTreeMap::new(),
}
}
pub fn add(&mut self, todo: Todo) {
let list = self.list.entry(todo.priority).or_insert_with(Vec::new);
list.push(todo);
}
pub fn todos(&self) -> impl Iterator<Item = &Todo> {
self.list.iter().flat_map(|(_, list)| list.iter())
}
pub fn unchecked(&self) -> impl Iterator<Item = &Todo> {
self.todos().filter(|t| !t.checked)
}
pub fn checked(&self) -> impl Iterator<Item = &Todo> {
self.todos().filter(|t| t.checked)
}
}
fn main() {
let mut list = TodoList::new();
list.add(Todo {
name: "A".to_string(),
checked: false,
priority: 10,
});
list.add(Todo {
name: "B".to_string(),
checked: false,
priority: 5,
});
list.add(Todo {
name: "C".to_string(),
checked: false,
priority: 6,
});
list.add(Todo {
name: "D".to_string(),
checked: true,
priority: 1,
});
println!("Unchecked todos:");
for todo in list.unchecked() {
todo.print();
}
println!("Checked todos:");
for todo in list.checked() {
todo.print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment