微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么Rust中的for循环可以遍历切片或迭代器,而不遍历数组?

如何解决为什么Rust中的for循环可以遍历切片或迭代器,而不遍历数组?

Rust 1.44.0中的for循环为什么可以在切片或迭代器而不是数组上进行迭代?例如,以下内容使我陷入循环:

遍历数组:

fn main() {
    let a = [1,2,3,4,5];

    for element in a {
        println!("element={}",element);
    }
}
error[E0277]: `[{integer}; 5]` is not an iterator
 --> main.rs:4:20
  |
4 |     for element in a {
  |                    ^ borrow the array with `&` or call `.iter()` on it to iterate over it
  |
  = help: the trait `std::iter::Iterator` is not implemented for `[{integer}; 5]`
  = note: arrays are not iterators,but slices like the following are: `&[1,3]`
  = note: required by `std::iter::IntoIterator::into_iter`

环绕切片(版本1):

fn main() {
    let a = &[1,element);
    }
}
element=1
element=2
element=3
element=4
element=5

环绕切片(版本2):

fn main() {
    let a = [1,5];

    for element in &a {
        println!("element={}",element);
    }
}
element=1
element=2
element=3
element=4
element=5

遍历数组迭代器:

fn main() {
    let a = [1,5];

    for element in a.iter() {
        println!("element={}",element);
    }
}
element=1
element=2
element=3
element=4
element=5

解决方法

编译器告诉您原因:因为数组不是迭代器。

不幸的是,有a long standing issue个用于数组的IntoIterator实现,加上这将是一个巨大的变化,并且生态系统中的一些已知问题是“仅此而已”,因此进展缓慢问题。

an accepted RFC可以向数组添加一个(明确称为)迭代器,但是it isn't available in Rust stable as of version 1.46

,

从 Rust 1.53.0 开始,array 的迭代行为发生了变化。现在我们可以按值迭代数组:

for i in [1,2,3] {
    ...
}

代码现在是合法的。详情请见 Announcing Rust 1.53.0

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。