Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update value in VecDeque?

Tags:

rust

deque

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?


1 Answers

Use back_mut

v.back_mut().unwrap().push_str(&str);

or just store reference in the deque

v.push_back(&mut str1);
like image 91
limon Avatar answered Jan 01 '26 20:01

limon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!