问题描述
这里有两个函数:
fn foo(iter: &mut I)在哪里我: std::iter::Iterator,{让 x = iter.by_ref();让 y = x.take(2);}fn bar(iter: &mut I)在哪里我: std::io::Read,{让 x = iter.by_ref();让 y = x.take(2);}
虽然第一个编译正常,但第二个给出了编译错误:
error[E0507]: 不能移出借来的内容-->src/lib.rs:14:13|14 |让 y = x.take(2);|^ 不能移出借来的内容
by_ref
和 take
的签名在 std::iter::Iterator
和 std::io 中几乎相同::Read
特征,所以我认为如果第一个编译,第二个也会编译.我哪里弄错了?
impl&'a mut I
的迭代器是第一个函数编译的原因.它为迭代器的所有可变引用实现了 Iterator
.
Read
特性 有等价物,但是,与Iterator
不同的是,Read
特性不在前奏,所以你需要使用 std::io::Read
使用这个实现:
使用 std::io::Read;//删除它以获得无法移出借来的内容"错误fn foo(iter: &mut I)在哪里I: std::iter::Iterator,{让 _y = iter.take(2);}fn bar(iter: &mut I)在哪里我: std::io::Read,{让 _y = iter.take(2);}
游乐场>
Here are two functions:
fn foo<I>(iter: &mut I)
where
I: std::iter::Iterator<Item = u8>,
{
let x = iter.by_ref();
let y = x.take(2);
}
fn bar<I>(iter: &mut I)
where
I: std::io::Read,
{
let x = iter.by_ref();
let y = x.take(2);
}
While the first compiles fine, the second gives the compilation error:
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:14:13
|
14 | let y = x.take(2);
| ^ cannot move out of borrowed content
The signatures of by_ref
and take
are almost identical in std::iter::Iterator
and std::io::Read
traits, so I supposed that if the first one compiles, the second will compile too. Where am I mistaken?
impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I
is the reason why the first function compiles. It implements Iterator
for all mutable references to iterators.
The Read
trait has the equivalent, but, unlike Iterator
, the Read
trait isn't in the prelude, so you'll need to use std::io::Read
to use this impl:
use std::io::Read; // remove this to get "cannot move out of borrowed content" err
fn foo<I, T>(iter: &mut I)
where
I: std::iter::Iterator<Item = T>,
{
let _y = iter.take(2);
}
fn bar<I>(iter: &mut I)
where
I: std::io::Read,
{
let _y = iter.take(2);
}
这篇关于为什么 by_ref().take() 的用法在 Iterator 和 Read trait 之间有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!