Creating an array from a tuple

I can create an array from a tuple like this:

let a = (1, 2, 3);
let b = [a.0, a.1, a.2];

      

Is there a way to do this without naming each element of the tuple? Something like:

let b = a.to_array();

      

+3


source to share


2 answers


There is currently no such feature, however it would be possible to extend the set of trait implementations From

to cover this usecase (and its converse).

This extension should be in the box core

due to orphan rules, but we can easily demonstrate it with custom traits:

use std::convert::Into;

trait MyFrom<T> {
    fn my_from(t: T) -> Self;
}

trait MyInto<U> {
    fn my_into(self) -> U;
}

impl<T, U> MyInto<U> for T
    where
        U: MyFrom<T>
{
    fn my_into(self) -> U { <U as MyFrom<T>>::my_from(self) }
}

impl<T> MyFrom<()> for [T; 0] {
    fn my_from(_: ()) -> Self { [] }
}

impl<T, A> MyFrom<(A,)> for [T; 1]
    where
        A: Into<T>,
{
    fn my_from(t: (A,)) -> Self { [t.0.into()] }
}

impl<T, A, B> MyFrom<(A, B)> for [T; 2]
    where
        A: Into<T>,
        B: Into<T>,
{
    fn my_from(t: (A, B)) -> Self { [t.0.into(), t.1.into()] }
}

      

Determine if it's easy enough to use:



fn main() {
    {
        let array: [i64; 0] = ().my_into();
        println!("{:?}", array);
    }
    {
        let array: [i64; 1] = (1u32,).my_into();
        println!("{:?}", array);
    }
    {
        let array: [i64; 2] = (1u32, 2i16).my_into();
        println!("{:?}", array);
    }
}

      

will print:

[]
[1]
[1, 2]

      

The reverse implementation will be just as simple, there is nothing mysterious here, it will not be just a template (hurray for macros!).

+5


source


No no. Moreover, you cannot even iterate over tuples. A tuple is not homogeneous, so it is not suitable for converting to a homogeneous type, such as a vector or an array.



You can write a macro to allow iteration over the contents of the total length tuple and collect them (as long as all its elements are of the same type), but you still have to access each element separately.

+2


source







All Articles