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)
?
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)
?
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:
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.
© 2022 - 2024 — McMap. All rights reserved.
From
, I'm pretty sure you getInto
for free, btw. So you can dolet tuple: (i32, String) = example.into();
. This is often nice because you can take advantage of type hinting. – Gildus