如何转换Vec& mut T> Vec& T? [英] How do you convert Vec<&mut T> to Vec<&T>?

查看:100
本文介绍了如何转换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.

这篇关于如何转换Vec&amp; mut T&gt; Vec&amp; T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆