Hi, there,
I'm learning rust according to rust-book, I have read through the book to chapter 8, and try to solve this hashmap exercise:
Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering" or “Add Amir to Sales." Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.
I just try to pratice the basic logic, read the input, get the department name, and add the employee name to a vector, the code like
use std::io;
fn main() {
println!("Hello, borrow!");
//department vector
let mut engineer: Vec<&str> = vec!["a","bc","de"];
loop {
//read the input command
println!("Please type your command like : Add Name to Department");
let mut cmd = String::new();
match io::stdin().read_line(&mut cmd){
Ok(n) => {
println!("{n} bytes read");
println!("cmdadd is {cmd}");
}
Err(_) => continue,
};
let cmdadd = cmd.trim();
//split the command string into a vector
let cmdvec:Vec<_> = cmdadd.split_whitespace().collect();
println!("cmdvec is : {:?}", cmdvec);
let depart = cmdvec[3];
//match the fourth element
match depart {
"Engineer" => {
println!("add someone to Engineer");
engineer.push(cmdvec[1]); //if i comment this line, the program can run
println!("engineer is {:?}", engineer);
},
"Sales" => {
println!("add someone to Sales");
},
_ => {
println!("the department doesn't exist");
},
};
}
}
use cargo check will give an error like
error[E0597]: `cmd` does not live long enough
--> p26_borrow\src\main.rs:20:22
|
12 | let mut cmd = String::new();
| ------- binding `cmd` declared here
...
20 | let cmdadd = cmd.trim();
| ^^^ borrowed value does not live long enough
...
30 | engineer.push(cmdvec[1]); //if i comment this line, the program can run
| -------- borrow later used here
...
41 | }
| - `cmd` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `p26_borrow` (bin "p26_borrow") due to previous error
what can i do to make this code work
thanks.