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 it without naming each element of the tuple? Something like:
let b = a.to_array();
To convert a tuple to an array(list) you can directly use the list constructor.
You can declare an array of tuple also. var employee: [number, string][]; employee = [[1, "Steve"], [2, "Bill"], [3, "Jeff"]]; TypeScript generates an array in JavaScript for the tuple variable. For example, var employee: [number, string] = [1, 'Steve'] will be compiled as var employee = [1, "Steve"] in JavaScript.
Python list method list() takes sequence types and converts them to lists. This is used to convert a given tuple into list. Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket.
if you mean array , no python arrays don't support tuples. Save this answer. Show activity on this post. The OP asked for an array, but this returns a list.
There is no such functionality at the moment, however it would be perfectly possible to extend the set of implementations of the From
trait to cover this usecase (and its reverse).
This extension would have to be in the core
crate because of the orphan rules, but we can readily 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()] }
}
Once define, 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 would be as easy, there's nothing mysterious here it's just boilerplate (hurray for macros!).
No, there isn't. What is more, you can't even iterate over tuples. The tuple is heterogeneous, so it's unfit for a conversion to a homogeneous type like a vector or an array.
You could write a macro to allow iteration over the contents of a tuple of a generic length and collect them (as long as all its elements are of the same type), but you would still have to access/process every element individually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With