Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

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

I've got a vector of mutable references:

struct T;
let mut mut_vec: Vec<&mut T> = vec![];

How can I pass (a copy of) it into a function that takes a vector of immutable references?

fn cool_func(mut immut_vec: Vec<&T>) {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>) {}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...