Xav
December 4, 2023, 3:18pm
1
Hi,
using structs in an enum, is there a way to type less than what I currently do ?
pub(crate) struct Is_u16(u16);
pub(crate) struct Is_u32(u32);
pub(crate) enum Variant {
t_u16(Is_u16),
t_u32(Is_u32)
}
and later
let v = Variant::t_u16(Is_u16(5));
Not talking about the length of the name, or the name themselves, but rather something that avoids the ::t_u16(Is_u16(
.
Thanks guys
jofas
December 4, 2023, 3:41pm
2
Under the assumption that your newtype structs serve a purpose in your real code, I'd "hide" them in constructors of Variant
so that your users don't need to explicitly wrap the integers when constructing Variant
. I'd use From<u16>
and From<u32>
for that:
#![allow(non_camel_case_types)]
#[derive(Debug, PartialEq)]
pub(crate) struct Is_u16(u16);
#[derive(Debug, PartialEq)]
pub(crate) struct Is_u32(u32);
#[derive(Debug, PartialEq)]
pub(crate) enum Variant {
t_u16(Is_u16),
t_u32(Is_u32),
}
impl From<u16> for Variant {
fn from(v: u16) -> Self {
Self::t_u16(Is_u16(v))
}
}
impl From<u32> for Variant {
fn from(v: u32) -> Self {
Self::t_u32(Is_u32(v))
}
}
fn main() {
let v16 = Variant::from(5u16);
let v32 = Variant::from(5u32);
assert_eq!(v16, Variant::t_u16(Is_u16(5)));
assert_eq!(v32, Variant::t_u32(Is_u32(5)));
}
Playground.
That turns let v = Variant::t_u16(Is_u16(5));
into let v = Variant::from(5u16);
which I think looks concise and quite pleasing.
1 Like
Xav
December 4, 2023, 3:42pm
3
Nice!
I will use your pattern instead.
thanks jofas
1 Like
system
Closed
March 3, 2024, 3:43pm
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.