How do you convert Vec<&mut T> to Vec<&T>?

2019-08-18 19:24发布

问题:

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?

回答1:

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.



标签: casting rust