rust - 从元组创建数组

标签 rust

我可以像这样从一个元组创建一个数组:

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/

相关文章:

rust - 无法对array::Viewer进行数学运算

exception - 使用 panic::catch_unwind 时抑制 Rust 中的 panic 输出

rust - 使用 From 特征触发将 u8 转换为枚举

input - print!() 在输入输入后执行

mysql - 如何将 Homebrew 安装的 mysql-client 与 diesel-cli 链接起来?

rust - 如何使用 Rust 生成最小的 wasm 文件?

rust - 如何将动态分配与以迭代器作为参数的方法一起使用?

rust - RUST 中这些行之间有什么区别?

for-loop - Rust 中 for 循环的命名中断

rust - 为什么闭包的可变引用参数不会比函数调用更长久?