[E0223] Why trait's associated types cannot be referred to directly?

Consider the following code:

struct Foo;

trait Bar {
    const CONST: usize;
    type Ty;
}

impl Bar for Foo {
    const CONST: usize = 10;
    type Ty = String;
}

We can get the CONST of Foo by writing Foo::CONST, omitting the <Foo as Bar>.
However, we must write <Foo as Bar>::Ty to refer to the associated type.

error[E0223]: ambiguous associated type
  --> src/main.rs:17:51
   |
17 |     assert_eq!(type_name::<String>(), type_name::<Foo::Ty>());
   |                                                   ^^^^^^^ help: use fully-qualified syntax: `<Foo as Bar>::Ty`

For more information about this error, try `rustc --explain E0223`.

The official documentation says that it's "due to internal limitations" without any roadmaps or something else.
I'd like to know what specifically is preventing this kind of code, and if any of these obstacles are currently being attempted to be addressed? I'm writing some web api wrappers, and being able to get associative types directly would improve the organization and experience of my codebase.

Related issues:

I don't have an actual answer, since the linked issues imply both "would be nice if we had a strategy for picking a trait in AST lowering or something, but we don't yet" and "we don't want to because it'd make more things a breaking change".

But the first link offers a potential workaround:

type BarTy<T> = <T as Bar>::Ty;

    assert_eq!(type_name::<String>(), type_name::<BarTy<Foo>>());

(Though it's unclear to me if this will help your use case or not.)

3 Likes

Thank you for your help, but it may still be a little less than appropriate. My current situation is mainly due to the fact that the current api itself has too much nesting and complexity, so using a wrapper doesn't optimize much. I'll look into using other code organization patterns to avoid this.

1 Like

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.