'as' in a type parameter for a trait

I found a way to write my generic (mostly with help of error messages from a compiler). I got this construction:

fn<T> ... where <T as std::ops::Div>::Output: Into<T> { ... }

Can someone explain me what as here means? I have intuition of it (output type parameter for trait Div for T should have Into implemented for T), but what is 'as' in this context?

A fitting alias in this context would be implements.

So what it means is "for any type T that implements std::ops::Div.

That statement is then used in the rest of the type level expression to get at the std::ops::Div::Output associated type, which in turn must implement Into<T> i.e. the Output can be converted into a value of type T.

1 Like

It’s the fully-qualified way to specify which associated item you’re talking about (an associated type in this case). The full construction with replacable parts highlighted is:

< SomeType as SomeTrait >::AssociatedItem 
  ^^^^^^^^    ^^^^^^^^^    ^^^^^^^^^^^^^^

Which means that you want the AssociatedItem that was defined in the implementation for SomeTrait for the type SomeType.

  • SomeType can be any kind of type specifier, including compound ones like Arc<Mutex<MyStruct>>,
  • SomeTrait needs to include the trait’s generic parameters (if it takes any), and
  • AssociatedItem is always a plain identifier of a type, constant, function, etc. from SomeTrait

Relevant section in the book (mostly focused on methods though):

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.