Alternatives to type aliases for generic parameters "from outer item"

⚓ rust    📅 2025-05-15    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 46 days ago. The information described in this article may have changed.

So I have the following situation

trait Trait {}

struct Wrapper<T>(T);

trait WrapperTrait {
    type AssociatedType;
    const ASSOCIATED_CONSTANT: usize;
}

impl<T> WrapperTrait for Wrapper<T> where T: Trait { ... }

And what I want to do is use these associated items in a generic function. While using them directly works just fine, defining an alias gives E0401 (can't use generic parameter from outer item).

fn f1<T: Trait>() {
    type U = <Wrapper<T> as WrapperTrait>::AssociatedType;
    const CONSTANT = <Wrapper<T> as WrapperTrait>::ASSOCIATED_CONSTANT;
}

For the type I thought of doing something like this but I can't make it work either, for the constant I can't really think of a workaround.

fn f2<T: Trait, U>()
where
    U = <Wrapper<T> as WrapperTrait>::AssociatedType,
{}

My questions are:

  1. Why is this limitation necessary? I get that "nested items are kind of like global items" but does that really make sense for type/constant aliases?
  2. What is the best solution to use these items without having to write out <Wrapper<T> as WrapperTrait>::AssociatedType each time. I can make it work using a macro but I want to believe there's a better way.

2 posts - 2 participants

Read full topic

🏷️ rust_feed