I am trying to make a CLI-like command emulator, but I get this error when editing:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:19:36
|
19 | commands[index] = &value.to_string();
| ^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
...
22 | if allowed_commands.contains(&commands[0].to_string()) {
| -------- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
For more information about this error, try `rustc --explain E0716`.
The code is as follows:
let mut varibles: HashMap<String, String> = HashMap::new();
loop {
let allowed_commands = vec!["help".to_string(), "quit".to_string(), "credits".to_string(), "set".to_string(), "settoken".to_string(), "ls".to_string(), "system".to_string(), "set".to_string(), "echo".to_string()];
let command = input("$> ");
let token = fs::read_to_string("/workspaces/codespaces-blank/spacetraders/src/token.txt").unwrap();
let mut commands: Vec<_> = command.split_whitespace().collect();
for (&ref key, &ref value) in varibles.clone().iter() {
println!("looking for {key}");
if commands.contains(&format!("${key}").as_str()) {
let index = commands.iter().position(|&r| r == key).unwrap();
commands[index] = &value.to_string();
}
if allowed_commands.contains(&commands[0].to_string()) {
match commands[0] {
"credits" => println!("You have {} credits", get_credits(&token).await),
"help" => println!("Available commands: help, quit, credits"),
"quit" => break,
"settoken" => fs::write("token.txt", commands[1]).unwrap(),
"ls" => {
let limit = *commands.get(1).unwrap_or_else(|| &"20");
let page = *commands.get(2).unwrap_or_else(|| &"1");
let limit = match limit.parse::<u64>() {
Ok(num) => num,
Err(_) => 20,
};
let page = match page.parse::<u64>() {
Ok(num) => num,
Err(_) => 1,
};
println!("{:#}", list_systems(&token, limit, page).await);
}
"system" => println!("{}", get_system(&token, commands[1].to_string()).await),
"set" => {
let name = *commands.get(1).unwrap_or_else(|| &"");
let value = *commands.get(2).unwrap_or_else(|| &"");
varibles.insert(name.to_string(), value.to_string());
}
"echo" => println!("{}", commands.get(1).unwrap_or_else(|| &"")),
_ => (),
}
} else {
println!("spacetraders: {}: command not found", commands[0]);
}
}
}}
How could I rewrite or improve the code so it will compile?