4

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)?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
edrevo
  • 1,147
  • 13
  • 17

1 Answers1

15

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    When you implement `From`, I'm pretty sure you get `Into` for free, btw. So you can do `let tuple: (i32, String) = example.into();`. This is often nice because you can take advantage of type hinting. – PitaJ Nov 07 '18 at 18:06