5

In Rust, is there any way to, at the type level, summon an Add implementation by using the LHS (Self) and RHS types in order to use its Output type (in say, the return type of a generic function)?

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
lloydmeta
  • 1,289
  • 1
  • 15
  • 25

1 Answers1

8

There is, although it does look like a bit of black magic.

You need to combine 3 bits of syntax:

  • the trait implementation of a type is accessible via <Type as Trait>
  • specifying the RHS simply requires passing it as a parameter Add<???>
  • and finally getting an associated type of a trait simply requires using Trait::OutputType (which may be ambiguous)

Combining the 3 together we get <Self as Add<RhsType>>::Output.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • Thanks ! This was exactly what I was looking for. Specifying RHS as the generic parameter was the missing part of the puzzle in my case. – lloydmeta Oct 20 '16 at 11:44