How to handle range in slices in Rust?

I understand that the preferred iteration method in Rust is the syntax for var in (range), but sometimes I would like to work on more than one of the elements in this range at a time.

From a Ruby point of view, I'm trying to find a way to do it (1..100).each_slice(5) do |this_slice|in Rust.

I'm trying something like

for mut segment_start in (segment_size..max_val).step_by(segment_size) {
    let this_segment = segment_start..(segment_start + segment_size).iter().take(segment_size);
}

but I keep getting errors that suggest that I bark the wrong tree of type. Documents are also not useful - they simply do not contain this use case.

What is the way to rust?

+4
source share
1 answer

Use chunks(or chunks_mutif you need volatility):

fn main() {
    let things = [5, 4, 3, 2, 1];

    for slice in things.chunks(2) {
        println!("{:?}", slice);
    }
}

Outputs:

[5, 4]
[3, 2]
[1]

Range , Vec ( ):

fn main() {
    let things: Vec<_> = (1..100).collect();

    for slice in things.chunks(5) {
        println!("{:?}", slice);
    }
}

, , Itertools::chunks_lazy:

extern crate itertools;

use itertools::Itertools;

fn main() {
    for chunk in &(1..100).chunks_lazy(5) {
        for val in chunk {
            print!("{}, ", val);
        }
        println!("");
    }
}

, :

fn main() {
    let mut range = (1..100).peekable();

    while range.peek().is_some() {
        for value in range.by_ref().take(5) {
            print!("{}, ", value);
        }
        println!("");
    }
}

, Ruby Rust , .

Ruby Enumerable , ( this_slice.object_id).

Rust . , , - , .

, Ruby:

fn main() {
    let mut range = (1..100).peekable();

    while range.peek().is_some() {
        let chunk: Vec<_> = range.by_ref().take(5).collect();

        println!("{:?}", chunk);
    }
}

, :

use std::iter::Peekable;

struct InefficientChunks<I>
    where I: Iterator
{
    iter: Peekable<I>,
    size: usize,
}

impl<I> Iterator for InefficientChunks<I>
    where I: Iterator
{
    type Item = Vec<I::Item>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.iter.peek().is_some() {
            Some(self.iter.by_ref().take(self.size).collect())
        } else {
            None
        }
    }
}

trait Awesome: Iterator + Sized {
    fn inefficient_chunks(self, size: usize) -> InefficientChunks<Self> {
        InefficientChunks {
            iter: self.peekable(),
            size: size,
        }
    }
}

impl<I> Awesome for I where I: Iterator {}

fn main() {
    for chunk in (1..100).inefficient_chunks(5) {
        println!("{:?}", chunk);
    }
}
+7

All Articles