Skip to content

Instantly share code, notes, and snippets.

@Marmiz
Created December 26, 2020 15:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Marmiz/b659c7835054d25513106e3804c4539f to your computer and use it in GitHub Desktop.
Save Marmiz/b659c7835054d25513106e3804c4539f to your computer and use it in GitHub Desktop.
Second portion of to-do cli in Rust
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)
}
}
@BytesPirate
Copy link

When I run cargo run -- add "make coffee", it had created a db,txt in root path, then I cannot run cargo run --add "make pancakes".

the terminus had error like this:

cargo run -- add "make pancakes"
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target\debug\rodo.exe add "make pancakes"`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseBoolError', src\main.rs:44:63
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\rodo.exe add "make pancakes"` (exit code: 101)

@BytesPirate
Copy link

I find this error in this code ,I code let record = format!("{}\t{}\n", k, v); into let record = format!("{}\t {}\n", k, v);, then I had this Bug, could you tell me why?

for (k, v) in self.map {
            let record = format!("{}\t{}\n", k, v);
            content.push_str(&record);
        }

@Marmiz
Copy link
Author

Marmiz commented Jul 27, 2023

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 -- and add.

Hope this helps.

@BytesPirate
Copy link

Thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment