为什么 IntoIter 不拥有这些值?

Why is IntoIter not owning the values?

我想迭代一个整数的字节:

use core::mem::size_of;

const SIZE: usize = size_of::<u64>();
    
fn main() {
    let x: u64 = 512;
    let mut buf: [u8; SIZE] = [0; SIZE];
    
    for (i, b) in x.to_be_bytes().into_iter().enumerate() {              
        buf[i] = b;
    }
}

编译器告诉我第 buf[i] = b; 行他 expected `u8`, found `&u8` 。但是为什么?

当我查看 IntoIterator 特性的实现时,拥有的数组类型 [T; N] into_iter() 方法 returns a std::array::IntoIter<T, N> 其中在 type Item = T 处实现 Iterator 特征。 T 不应该在此处评估为 u8 吗?

为什么迭代器返回 &u8 个引用而不是拥有 u8 个字节?

Rust 文档提到 array 的这种行为:

Prior to Rust 1.53, arrays did not implement IntoIterator by value, so the method call array.into_iter() auto-referenced into a slice iterator. Right now, the old behavior is preserved in the 2015 and 2018 editions of Rust for compatibility, ignoring IntoIterator by value. In the future, the behavior on the 2015 and 2018 edition might be made consistent to the behavior of later editions.

如果您使用 Rust 2018,您将获得参考资料,但目前您可以使用 IntoIterator::into_iter(array)

在循环中取消引用 b 将提示:

  |
9 |     for (i, b) in x.to_be_bytes().into_iter().enumerate() {
  |                                   ^^^^^^^^^
  |
  = note: `#[warn(array_into_iter)]` on by default
  = warning: this changes meaning in Rust 2021
  = note: for more information, see issue #66145 <https://github.com/rust-lang/rust/issues/66145>

这是一个例子:

use core::mem::size_of;

const SIZE: usize = size_of::<u64>();

fn main() {
    let x: u64 = 512;
    let mut buf: [u8; SIZE] = [0; SIZE];

    for (i, b) in IntoIterator::into_iter(x.to_be_bytes()).enumerate() {
        buf[i] = b;
    }
}

具有新行为的 Rust 2021 版本可能会在今年 10 月登陆。有关详细信息,请参阅 Rust Blog, "The Plan for the Rust 2021 Edition"