Is there any way of converting a struct to a tuple?
Asked Answered
J

2

5

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

Jud answered 7/11, 2018 at 17:3 Comment(0)
B
17

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:

Belligerency answered 7/11, 2018 at 17:7 Comment(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.Gildus
F
2

The derive_getters crate has a derive macro Dissolve which can auto-convert a given struct to a tuple.

Example:

use derive_getters::Dissolve;

#[derive(Dissolve)]
struct Params
{
    float: f32,
    int: i32,
}

let p = Params { ... };
let (f, i): (f32, i32) = p.dissolve();

I know this is an old post, but I figure I'd help anyone else popping by looking for answers.

Forge answered 20/9 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.