Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the `cycle()` method exists if `ChunksMut` is never `Clone?`

The https://doc.rust-lang.org/std/slice/struct.ChunksMut.html has the cycle method: https://doc.rust-lang.org/std/iter/struct.Cycle.html#method.cycle that works only when Self: Clone

However, ChunksMut does not implement Clone, therefore I cannot do this:

fn main() {
    let a = &[1,2,3,4,5,6];
    let mut chunks = a.chunks_mut(2);
    let cycle = chunks.cycle();
    for c in cycle {
        
    }
}

Why the cycle() method exists if ChunksMut is never Clone?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

ChunksMut implements the Iterator trait.

impl<'a, T> Iterator for ChunksMut<'a, T>

And to impl an Iterator trait for ChunksMut all the trait methods have to be implemented and cycle is one among them.

fn cycle(self) -> Cycle<Self>
where
    Self: Clone, 

For example, following code will not compile because SampleStruct does not implement the SampleTrait trait methods.

pub trait SampleTrait {
    fn trait_method_one(&self) -> String;
    fn trait_method_two(&self) -> String;
}

pub struct SampleStruct;

impl SampleTrait for SampleStruct {}

fn main() {}

Rust compiler produces the following error message in this case.

not all trait items implemented, missing: `trait_method_one`, `trait_method_two`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading