为什么 by_ref().take() 的用法在 Iterator 和 Read trait 之间有所不同? [英] Why does the usage of by_ref().take() differ between the Iterator and Read traits?

查看:32
本文介绍了为什么 by_ref().take() 的用法在 Iterator 和 Read trait 之间有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有两个函数:

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_reftake 的签名在 std::iter::Iteratorstd::io 中几乎相同::Read 特征,所以我认为如果第一个编译,第二个也会编译.我哪里弄错了?

解决方案

impl<'a, I: Iterator + ?Sized>&'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);
}

Playground

这篇关于为什么 by_ref().take() 的用法在 Iterator 和 Read trait 之间有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆