Correct way to write it?

Hi,
Here is the playground.

If fn prepare actually used the fields from struct A (A still can accept different values type for its members), is it possible to minimize the typing for the generic parameters of say <u16, u16>, in MyTrait<u16, u16> for A<u16, u16> ?

Thanks

I’ve read it about 5 times, I can say for sure that I’m not sure what you’re asking. Perhaps try to write some more, explain what you’re asking in more detail, perhaps demonstrate with more code examples what kind of effect you’d like to achieve.

Do you mean, save typing by using default type params like this?:

struct A<T, U = T> {
        index: T,
        outer: U
}

trait MyTrait<T, U = T> {
        fn prepare(&self, inp: T, out: U);
}

impl MyTrait<u16> for A<u16> {
        fn prepare(&self, inp: u16, out: u16) {

                println!("A u16 u16 {} {}", inp, out);
        }
}

playground

Sorry,
I just wanted to know if I could type less for the exact same semantic.

Did I answer your question? If not, please explain why.

Sure, you could define a macro. E.g.

macro_rules! impl_my_trait_a {
    ($T:ty, $U:ty, |$inp:ident, $out:ident| $body:block) => {
        impl MyTrait<$T, $U> for A<$T, $U> {
            fn prepare(&self, $inp: $T, $out: $U) $body
        }
    }
}

// N.B. by using a sort of “pseudo closure syntax” approach
// and by calling with `macro_name!( … );` instead of `macro_name!{ … }`,
// these macro calls will have full rustfmt support. 

impl_my_trait_a!(u32, u32, |inp, out| {
    println!("A u32 {} {}", inp, out);
});

impl_my_trait_a!(u16, u32, |inp, out| {
    println!("A u16 u32 {} {}", inp, out);
});

impl_my_trait_a!(u16, u16, |inp, out| {
    println!("A u16 u16 {} {}", inp, out);
});

Ah, or if it was just about the repetition in each <u16, u16>, then @jumpnbrownweasel has already showed how that might work.

2 Likes

Thanks, I will keep it that way.

So nothing I can do to type less here:
impl MyTrait<u16, u32> for A<u16, u32> ?

Edit: no forget it, there is no logic for less typing with it, one has to take into account the generics types for the trait and the struct.

Solved!

Thank a lot guys

1 Like