我想对整数的字节进行迭代:
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()方法返回一个std::array::IntoIter<T, N>,该std::array::IntoIter<T, N>实现了type Item = T所在的Iterator特征。T不应该在这里评估为u8吗?
为什么迭代器返回的是&u8引用而不是拥有的u8字节?
发布于 2021-09-28 09:36:01
Rust文档提到了array的这种行为
在Rust 1.53之前,数组没有按值实现IntoIterator,因此方法调用自动引用到片迭代器中的
array.into_iter()。现在,旧的行为保留在2015年和2018年版本的锈蚀兼容性,忽略了IntoIterator的价值。在未来,2015年和2018年版的行为可能会与以后版本的行为一致。
如果您使用的是锈菌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;
}
}锈蚀2021年版,新的行为,很可能会在今年10月登陆。有关详细信息,请参阅铁锈博客,“铁锈2021版计划”。
https://stackoverflow.com/questions/69359085
复制相似问题