Is there any way of converting a struct to a tuple?

Viewed 1832

Given something like this:

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

Is there any built-in method or any trait I can implement that will allow me to obtain a tuple of (i32, String)?

1 Answers

Is there any way of converting a struct to a tuple

Yes.

any built-in method or any trait I can implement

Not really.


I'd implement From, which is very generic:

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

You'd use it like this:

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

See also:

Related