【问题标题】:Using "moved" values in a function在函数中使用“移动”值
【发布时间】:2016-02-13 05:01:21
【问题描述】:

我想学习 Rust,正在编写一个小程序来处理声音问题。我有一个带有这个签名的函数:

fn edit_show(mut show: &mut Vec<Que>) {
    show.sort_by(|a, b| que_ordering(&a.id, &b.id));
    loop {
        println!("Current ques");
        for l in show {
            println!("{}", que_to_line(&l));
        }
    }
}

我收到一个错误:

使用移动值:'show'

我找不到有关如何解决此问题的任何信息。这似乎是一个奇怪的排序错误,因为(我假设)如果我要在主函数中执行此操作,我传入的值似乎毫无用处。

【问题讨论】:

标签: sorting rust


【解决方案1】:

解决方案

你的问题出在这一行:

for l in show {
    ...
}

这会消耗向量show。如果你只想借用它的元素,你应该写:

for l in &show {
    ...
}

如果你想可变地借用它们,写for l in &amp;mut show

说明

Rust for 循环需要一个实现 IntoIterator 的类型。首先要注意:IntoIterator 是为每个Iterator 实现的。见:

impl<I> IntoIterator for I where I: Iterator

现在让我们搜索Vec impls:

impl<T> IntoIterator for Vec<T> {
    type Item = T
    ...
}

impl<'a, T> IntoIterator for &'a Vec<T> {
    type Item = &'a T
    ...
}

impl<'a, T> IntoIterator for &'a mut Vec<T> {
    type Item = &'a mut T
    ...
}

在这里你可以看到它是直接为Vec 实现的,也可以用于引用它。我希望这三个 impl 块不言自明。

【讨论】:

  • 值得注意的是,在某些情况下&amp;mut T 会自动重新借用,因此不算作移动。知道哪个是哪个似乎是一门黑暗的艺术。
  • 在我的情况下,答案似乎是让它 show.iter() 而不是 &show 导致类型冲突
  • @SebastianMalton 你确定吗? &amp;showshow.iter() 在你的情况下应该做同样的事情......
  • 是的,我可以稍后发布编译器日志
猜你喜欢
  • 2018-10-30
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2020-03-22
  • 1970-01-01
相关资源
最近更新 更多