Is there any way to unpack an iterator into a tuple?

This may not be exactly what you asked for, but I suppose you rarely want to convert an arbitrarily large vector to a tuple anyway. If you just want to extract the first few elements of a vector into a tuple, you can do so using slice pattern matching:

fn main() {
    let v = vec![1, 2, 3];
    let (a, b) = match &v[..] {
        &[first, second, ..] => (first, second),
        _ => unreachable!(),
    };
    assert_eq!((a, b), (1, 2));
}

The itertools crate has methods like tuples and next_tuple that can help with this.

use itertools::Itertools; // 0.9.0

fn main() {
    let v = vec![1, 2, 3];
    let (a, b) = v.iter().next_tuple().unwrap();

    assert_eq!(a, &1);
    assert_eq!(b, &2);
}

Tags:

Rust