锈蚀中的不可变访问

  • 本文关键字:不可变 访问 rust
  • 更新时间 :
  • 英文 :


我是python的新手,并且在python中广泛使用了函数式风格。

我试图做的是接受一个字符串(切片)(或任何可迭代对象)并使用对当前索引和下一个索引的引用进行迭代。这是我的尝试:

fn main() {
// intentionally immutable, this should not change
let x = "this is a
multiline string
with more
then 3 lines.";
// initialize multiple (mutable) iterators over the slice
let mut lineiter = x.chars();
let mut afteriter = x.chars();
// to have some reason to do this
afteriter.skip(1);
// zip them together, comparing the current line with the next line
let mut zipped = lineiter.zip(afteriter);
for (char1, char2) in zipped {
println!("{:?} {:?}", char1, char2);
}
}

我认为应该可以获得不同的迭代器,这些迭代器在切片中具有不同的位置,但引用内存的相同部分而无需复制字符串,但我得到的错误如下:

error[E0382]: use of moved value: `afteriter`
--> /home/alex/Documents/projects/simple-game-solver/src/src.rs:15:35
|
10 |     let afteriter = x.chars();
|         --------- move occurs because `afteriter` has type `std::str::Chars<'_>`, which does not implement the `Copy` trait
11 |     // to have some reason to do this
12 |     afteriter.skip(1);
|     --------- value moved here
...
15 |     let mut zipped = lineiter.zip(afteriter);
|                                   ^^^^^^^^^ value used here after move

我还收到一条警告,告诉我压缩不需要可变。

是否可以在单个变量上实例化多个迭代器,如果是,如何做到这一点?

是否可以在单个变量上实例化多个迭代器,如果是,如何做到这一点?

如果您检查签名和文档Iterator::skip

fn skip(self, n: usize) -> Skip<Self>

创建跳过前 n 个元素的迭代器。

在它们被消耗后,其余的元素被产生。不要直接重写此方法,而是重写第 n 个方法。

您可以看到它按值获取self(使用输入迭代器)并返回新的迭代器。这不是就地使用迭代器前n个元素的方法,而是将现有迭代器转换为跳过前 n 个元素的方法。

所以代替:

let mut afteriter = x.chars();
afteriter.skip(1);

你只需写:

let mut afteriter = x.chars().skip(1);

我还收到一条警告,告诉我压缩不需要可变。

这是因为 Rustfor循环使用了IntoIterator特征,它将可迭代对象移动到循环中。它不是在创建一个可变的引用,它只是消耗 RHS 是什么。

因此,它不关心变量的可变性。如果您显式迭代,或者如果您调用其他"终端"方法(例如mutnthtry_foldall),或者如果你想迭代可变引用(虽然这对集合最有用),但不要将迭代器交给其他组合器方法或for循环。

一个 for 循环需要self,如果你愿意的话。就像for_each事实上所做的那样。

感谢@Stargateur给我解决方案。.skip(1)获取 afteriter 的所有权,并将所有权返回给没有第一个元素的版本。之前发生的事情是.skip失去了所有权,因此变量不能再变异了(我很确定)

最新更新