首页 > 解决方案 > 从 Rc 中获取字符串向量>> 在锈

问题描述

我有一个接受Vec<String>值的函数。我想对包含在里面的值使用这个函数my_ref,所以我需要Vec<String>Rc<RefCell<Vec<String>>>.

我想我可以通过取消引用 my 来做到这一点my_ref,就像我对 a Rc<RefCell<f32>>>orRc<RefCell<i32>>>值一样:

use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let my_ref = Rc::from(RefCell::from(vec![
        "Hello 1".to_string(),
        "Hello 2".to_string(),
    ]));
    let my_strings: Vec<String> = *my_ref.borrow();
    let count = count_strings(my_strings);
}

fn count_strings(strings: Vec<String>) -> usize {
    strings.len()
}

但这样做会导致取消引用错误:

error[E0507]: cannot move out of dereference of `Ref<'_, Vec<String>>`
cannot move out of dereference of `Ref<'_, Vec<String>>`
move occurs because value has type `Vec<String>`, which does not implement the `Copy` trait

那么,我如何正确地从 a 中提取Vec<String>a Rc<RefCell<Vec<String>>>

标签: rust

解决方案


RefCell::borrow返回一个引用,而不是一个拥有的值,这就是你有这样一个错误的原因。我可以为这个问题命名两个不同的解决方案。

提升Rc为独资型

Rc::try_unwrap能够检查是否有其他对数据的引用。如果它是唯一的,它可以安全地转换为内部类型。然后,一个拥有的RefCell可以通过into_inner函数转换为它的内部。

let my_ref = Rc::from(RefCell::new(vec![..]));
let inner: Vec<_> = Rc::try_unwrap(my_ref).expect("I hereby claim that my_ref is exclusively owned").into_inner();

替换内在价值

如果出于某种原因你想获取已经被引用的内部值,你可以考虑替换它。请注意,您需要为类型创建一个适当的值(即 with trait Default)。这是示例:

let my_ref = Rc::from(RefCell::new(vec![..]));
let inner: Vec<_> = my_ref.borrow_mut().take();
// or
let inner: Vec<_> = my_ref.borrow_mut().replace(vec![]);

推荐阅读