I've got a vector of mutable references:
type T = String;
let mut mut_vec: Vec<&mut T> = vec![];
I want to pass (a copy of) it into a function that takes a vector of immutable references:
fn cool_func(mut immut_vec: Vec<&T>) -> bool {false}
How can I do this?
You can dereference and reborrow the mutable references, then add them to a new Vec
:
fn main() {
let mut st = String::new();
let mut_vec = vec![&mut st];
let immut_vec = mut_vec.into_iter().map(|x| &*x).collect();
cool_func(immut_vec);
}
fn cool_func(_: Vec<&String>) -> bool {
false
}
Note however, that this consumes the original Vec
- you can't really get around this, as if the original Vec
still existed, you'd have both mutable and immutable references to the same piece of data, which the compiler will not allow.