rust - 从 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>>>
?
解决方案
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![]);
推荐阅读
- ruby-on-rails - 按名称对哈希数组排序,但将具有相同 ID 的名称放在一起
- android - 为什么我们需要使用
属性? - r - GME 的“isectpolyrst”的 R 脚本是什么?
- java - 如何从Java中的路径获取目录名称?
- django - 使用终端界面自定义 django 管理页面
- javascript - 如何让 Google 表格绑定的 code.js 从未包含的远程 .js 文件中读取和操作 JavaScript?
- windows - 是否有任何可能的方式为非管理员用户提供所有服务(Windows 和第 3 方)访问权限?
- python - Glob 只返回文件夹中的第一个文件
- tmux - 如何移动 Tmux 窗格
- parentheses - 如何修复第 4 行中发生的“预期右括号”:winbugs 中的 tau0*(t[j+1]-t[j])