Reputation:
I want to store value in a VecDeque
and after it updates the value:
use std::collections::VecDeque;
fn main() {
let mut v = VecDeque::new();
let mut str1 = String::from("Hello");
v.push_back(str1);
let str = String::from(" World");
str1.push_str(&str);
}
Compiling playground v0.0.1 (/playground)
error[E0382]: borrow of moved value: `str1`
--> src/main.rs:10:5
|
5 | let mut str1 = String::from("Hello");
| -------- move occurs because `str1` has type `std::string::String`, which does not implement the `Copy` trait
6 |
7 | v.push_back(str1);
| ---- value moved here
...
10 | str1.push_str(&str);
| ^^^^ value borrowed here after move
How can I add item to collection and after it update this item?
Upvotes: 3
Views: 450
Reputation:
My working example:
use std::collections::VecDeque;
fn main() {
let mut v = VecDeque::new();
let mut str1 = String::from("Hello");
v.push_back(str1);
let mut str2 = String::from(" World");
match v.back_mut() {
Some(value) => value.push_str(&str2),
None => println!("Error")
}
match v.back() {
Some(value) => println!("{}", value),
None => println!("Error2")
}
}
Upvotes: 3
Reputation: 917
Use back_mut
v.back_mut().unwrap().push_str(&str);
or just store reference in the deque
v.push_back(&mut str1);
Upvotes: 4