Created
December 26, 2020 15:35
-
-
Save Marmiz/b659c7835054d25513106e3804c4539f to your computer and use it in GitHub Desktop.
Second portion of to-do cli in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
use std::io::Read; | |
use std::str::FromStr; | |
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::new().expect("Initialisation of db failed"); | |
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 new() -> Result<Todo, std::io::Error> { | |
let mut f = std::fs::OpenOptions::new() | |
.write(true) | |
.create(true) | |
.read(true) | |
.open("db.txt")?; | |
let mut content = String::new(); | |
f.read_to_string(&mut content)?; | |
let map: HashMap<String, bool> = content | |
.lines() | |
.map(|line| line.splitn(2, '\t').collect::<Vec<&str>>()) | |
.map(|v| (v[0], v[1])) | |
.map(|(k, v)| (String::from(k), bool::from_str(v).unwrap())) | |
.collect(); | |
Ok(Todo { map }) | |
} | |
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
Hi @iA10N3, is this the command you are running?
cargo run --add "make pancakes"
.If so that is not correct. When running a binary with cargo run, the arguments are passed into the binary after two dashes. See here for more detials.
So the correct command should be:
cargo run -- add "make pancakes"
Notice the space between
--
andadd
.Hope this helps.