trexinf14s
trexinf14s

Reputation: 291

Rust: impl From<_> for usize, u64, u32, etc

Let S be a struct. I want to implement From for all uint types. Is there a terse way to do this?

E.g., I want to write this code

impl From<S> for usize {
    fn from(s: S) -> usize {
        s.field_a + s.field_b    
    }
}

impl From<S> for u64 {
    fn from(s: S) -> u64 {
        s.field_a + s.field_b    
    }
}

impl From<S> for u32 {
    fn from(s: S) -> u32 {
        s.field_a + s.field_b    
    }
}

...

as

impl From<S> for uint {
    fn from(s: S) -> uint {
        s.field_a + s.field_b    
    }
}

My first thought was to use traits to group all the uints a la how we pass traits as parameters. Here's my attempt:

use std::ops::Add;

impl From<S> for impl From + Add {
    fn from<T: From + Add>(s: S) -> T {
        T::from(s.field_a) + T::from(s.field_b)
    }
}

But this doesn't work and feels janky (uints aren't just things that impl From and Add).

Don't know where to go from here! Any help would be appreciated!

Upvotes: 5

Views: 2475

Answers (1)

SCappella
SCappella

Reputation: 10444

A macro could work. (playground)

struct S {
    field_a: u8,
    field_b: u8,
}

macro_rules! impl_from_s {
    ($($uint_type: ty),*) => {
        $(
            impl From<S> for $uint_type {
                fn from(s: S) -> $uint_type {
                    <$uint_type>::from(s.field_a) + <$uint_type>::from(s.field_b)
                }
            }
        )*
    }
}

impl_from_s!(u8, u16, u32, u64, u128);

Upvotes: 8

Related Questions