Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the associated Output type of an Add implementation given LHS and RHS types

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)?

like image 844
lloydmeta Avatar asked Oct 20 '16 06:10

lloydmeta


1 Answers

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.

like image 68
Matthieu M. Avatar answered Sep 30 '22 04:09

Matthieu M.