如何转换Vec& mut T> Vec& T?

如何转换Vec& mut T> Vec& T?

问题描述:

我有一个可变引用向量:

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}

我该怎么做?

您可以取消引用并重新借用可变引用,然后将它们添加到新的 Vec

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
}

但是请注意,这会消耗原始的 Vec -您无法真正解决这个问题,就像原始的 Vec 仍然存在一样,你们两个都变了和对同一数据的不可变引用,编译器将不允许。

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.