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

こ雲淡風輕ζ 提交于 2020-01-06 06:48:08

问题


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.



来源:https://stackoverflow.com/questions/56754101/how-do-you-convert-vecmut-t-to-vect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!