First of all, I am sorry for that I cannot compare some duplicate questions to mine because I am a beginner in Rust. Possibly duplicate question
The compiler outputs an error for my code as:
error[E0507]: cannot move out of index of `std::vec::Vec<std::rc::Rc<dyn T>>`
--> src/lib.rs:30:18
|
30 | let V_last = data.V[V_lastIdx];
| ^^^^^^^^^^^^^^^^^
| |
| move occurs because value has type `std::rc::Rc<dyn T>`, which does not implement the `Copy` trait
| help: consider borrowing here: `&data.V[V_lastIdx]`
Please help me to solve problem.
use std::collections::HashMap;
use std::rc::Rc;
trait T {
fn main(&self, data: &mut Data) -> ();
}
#[derive(Clone)]
struct S1 {
val: usize,
t: Rc<dyn T>,
}
struct S2 {
val: usize,
}
impl T for S1 {
fn main(&self, data: &mut Data) -> () {
data.V.push(Rc::new(S2 { val: 123 }));
}
}
impl T for S2 {
fn main(&self, data: &mut Data) -> () {}
}
struct Data {
// Up to 1 instance which may hold about 30MB at most.
V: Vec<Rc<dyn T>>,
name_match: HashMap<String, (usize, usize)>,
}
fn round(data: &mut Data) {
let V_lastIdx = data.V.len() - 1;
let V_last = data.V[V_lastIdx];
return V_last.main(data);
}
After I followed the compiler suggestion, a new error says as follows.
help: consider borrowing here: `&data.V[V_lastIdx]`
error[E0502]: cannot borrow `*data` as mutable because it is also borrowed as immutable
--> src/lib.rs:34:11
let V_last= &data.V[V_lastIdx];
| ------ immutable borrow occurs here
34 | return V_last.main(data);
| ^^^^^^^----^^^^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
Now I have selected the answer, I notice that my original code could be more simple as following link, with the solution code borrowed from the selected answer.