有什么方法可以将结构转换为元组吗?

时间:2018-11-07 17:03:33

标签: rust

给出类似这样的内容:

struct Example {
    a: i32,
    b: String,
}

我可以实现任何内置方法或任何特征来让我获得(i32, String)元组吗?

1 个答案:

答案 0 :(得分:10)

  

有什么方法可以将结构转换为元组

是的

  

我可以实现的任何内置方法或任何特征

不是真的。


我将实现From,这是非常通用的:

impl From<Example> for (i32, String) {
    fn from(e: Example) -> (i32, String) {
        let Example { a, b } = e;
        (a, b)
    }
}

您将像这样使用它:

let tuple = <(i32, String)>::from(example);
let tuple: (i32, String) = example.into();

另请参阅: