Skip to content

Instantly share code, notes, and snippets.

@Marmiz
Created December 26, 2020 14:45
Show Gist options
  • Save Marmiz/b67e98c2fc7be3561d124294cf3cb6ac to your computer and use it in GitHub Desktop.
Save Marmiz/b67e98c2fc7be3561d124294cf3cb6ac to your computer and use it in GitHub Desktop.
First portion of to-do cli in Rust
use std::collections::HashMap;
fn main() {
let action = std::env::args().nth(1).expect("Please specify an action");
let item = std::env::args().nth(2).expect("Please specify an item");
let mut todo = Todo {
map: HashMap::new(),
};
if action == "add" {
todo.insert(item);
match todo.save() {
Ok(_) => println!("todo saved"),
Err(why) => println!("An error occurred: {}", why),
}
};
}
struct Todo {
// use rust built in HashMap to store key - val pairs
map: HashMap<String, bool>,
}
impl Todo {
fn insert(&mut self, key: String) {
// insert a new item into our map.
// we pass true as value.
self.map.insert(key, true);
}
fn save(self) -> Result<(), std::io::Error> {
let mut content = String::new();
for (k, v) in self.map {
let record = format!("{}\t{}\n", k, v);
content.push_str(&record)
}
std::fs::write("db.txt", content)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment