我可以像这样从一个元组创建一个数组:
let a = (1, 2, 3);
let b = [a.0, a.1, a.2];
有没有办法不用命名元组的每个元素?像这样的东西:
let b = a.to_array();
最佳答案
目前没有这样的功能,但是完全有可能扩展 From
特性的实现集来涵盖这个用例(及其反向) ).
由于孤儿规则,这个扩展必须在 core
crate 中,但我们可以很容易地用自定义特征来演示它:
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()] }
}
一旦定义,就很容易使用:
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);
}
}
将打印:
[] [1] [1, 2]
反向实现也很简单,这里没有什么神秘的,只是样板文件(为宏欢呼!)。
关于rust - 从元组创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44041673/