Get next `n` items from an iterator with const generics

Example:

let [a, b, c] = "lorem ipsum dolor sit amet"
    .split(' ')
    .next_n::<3>()
    .unwrap();

assert_eq!((a, b, c), ("lorem", "ipsum", "dolor"));

Could this be implemented with min_const_generics? Is something like this planned?

The alternative is much less elegant:

let mut iter = "lorem ipsum dolor sit amet".split(' ');
let a = iter.next().unwrap();
let b = iter.next().unwrap();
let c = iter.next().unwrap();

assert_eq!((a, b, c), ("lorem", "ipsum", "dolor"));

or requires allocating a Vec:

let v = "lorem ipsum dolor sit amet"
    .split(' ')
    .take(3)
    .collect::<Vec<_>>();

assert_eq!((v[0], v[1], v[2]), ("lorem", "ipsum", "dolor"));
1 Like
use itertools::Itertools;
fn main() {
    let (a, b, c) = "lorem ipsum dolor sit amet"
        .split(' ')
        .next_tuple()
        .unwrap();

    assert_eq!((a, b, c), ("lorem", "ipsum", "dolor"));
}

(playground)

just to mention an elegant alternative for up to 4 elements

3 Likes
4 Likes

Thanks!

For what is worth, I would write this as

let mut iter = "lorem ipsum dolor sit amet".split(' ');
let (a, b, c) = match (iter.next(), iter.next(), iter.next()) {
    (Some(a), Some(b), Some(c)) => (a, b, c),
    _ => panic!(),
};

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.