Why does the usage of by_ref().take() differ between the Iterator and Read traits?

前端 未结 2 1102
清酒与你
清酒与你 2020-12-06 17:21

Here are two functions:

fn foo(iter: &mut I)
where
    I: std::iter::Iterator,
{
    let x = iter.by_ref();
    let y = x.take(         


        
2条回答
  •  一生所求
    2020-12-06 17:54

    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(iter: &mut I)
    where
        I: std::iter::Iterator,
    {
        let _y = iter.take(2);
    }
    
    fn bar(iter: &mut I)
    where
        I: std::io::Read,
    {
        let _y = iter.take(2);
    }
    

    Playground

提交回复
热议问题