用Rust循环遍历RefCell包装的Vec [英] Looping through a RefCell wrapped Vec with Rust

查看:607
本文介绍了用Rust循环遍历RefCell包装的Vec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含RefCell的结构,用于在向量中存储可变值,并且我想遍历其值.

I have a struct that contains a RefCell for storing mutable values within a vector, and I'd like to loop over its values.

添加元素不会引起任何问题,但是当尝试将借用的向量转换为迭代器时,它将引发:

Adding an element causes no problems, but when attempting to convert the borrowed vector into an iterator it throws:

错误:无法移出借用的内容[E0507]

error: cannot move out of borrowed content [E0507]

为什么借款即使是不变的,也很重要?我不明白,当变量的内容甚至没有变化时,为什么编译器会将此标记为潜在问题.

Why does the borrow even matter, if it's immutable? I don't understand why the compiler would mark this as a potential issue when the content of the variable doesn't even change.

我可以通过克隆解决所有权问题,但是为什么首先需要这样做?克隆我要遍历的结构可能会花费很高的CPU成本,并且我希望不必这样做.

I can get around the ownership issue by cloning it, but why do I need to do that in the first place? Cloning the structure I'm trying to loop over is probably going to have a high CPU cost and I'd prefer not to have to do it if possible.

我要实现的示例:

fn main() {
    use std::cell::RefCell;
    let c = RefCell::new(vec![1, 2, 3]);

    let arr = c.borrow();

    for i in arr.into_iter() {
        println!("{}", i);
    }
}

这里是否有我想念的东西,还是Rust对此过于谨慎?

Is there something I'm missing here or is Rust being overly cautious about this?

如果有人能填补我对它的工作原理的理解上的空白,将不胜感激.

Would appreciate it if someone could fill any gaps in my understanding of how this works.

推荐答案

看来问题在于Vec.into_iterVec.iter之间存在差异.要解决,请更改:

It appears the issue was in there being a difference between Vec.into_iter and Vec.iter. To solve, change:

for i in arr.into_iter() {
    println!("{}", i);
}

收件人:

for i in arr.iter() {
    println!("{}", i);
}

有效地在锈 .

这篇关于用Rust循环遍历RefCell包装的Vec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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