【问题标题】:Why is IntoIter not owning the values? [duplicate]为什么 IntoIter 不拥有这些值? [复制]
【发布时间】:2021-11-20 08:09:01
【问题描述】:

我想遍历一个整数的字节:

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 `&amp;u8` 。但为什么呢?

当我查看拥有数组类型[T; N]IntoIterator 特征的实现时,into_iter() 方法返回一个std::array::IntoIter&lt;T, N&gt;,它实现了Iterator 特征,其中type Item = TT 不应该在这里评估为u8 吗?

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

【问题讨论】:

    标签: types rust ownership


    【解决方案1】:

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

    在 Rust 1.53 之前,数组没有按值实现 IntoIterator,因此方法调用 array.into_iter() 自动引用到切片迭代器中。现在,为了兼容性,旧的行为在 2015 和 2018 版本的 Rust 中保留,按值忽略 IntoIterator。未来,2015 和 2018 版本的行为可能会与后续版本的行为保持一致。

    如果您使用 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" 了解更多信息。

    【讨论】:

    • rust 1.56 对于 2021 版应该是稳定的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多