Can an associated type be used as a type constructor?

The following code is a small example of a TryFrom implementation for some structs A and B, with C being used as the associated error type.

struct A;
struct B;
struct C;

impl TryFrom<A> for B {
    type Error = C;

    fn try_from(value: A) -> Result<Self, Self::Error> {
        if some_condition() {
            Ok(Self)
        } else {
            Err(Self::Error) // compiler Error
            // Err(C) would work
        }
    }
}

Why can both Self and Self::Error be used in the return type of try_from, but only Self can be used to actually construct the return type?

Thanks for your assistance!

It's a general fact about type aliases. This doesn't work either:

struct Foo;

type Bar = Foo;

fn test() -> Bar {
    Bar
}
error[E0423]: expected value, found type alias `Bar`
 --> src/lib.rs:7:5
  |
7 |     Bar
  |     ^^^
  |
  = note: can't use a type alias as a constructor

As for Self working even though it looks like an alias, well, it is a special case. I'm pretty confident that you have not always been able to use Self like this. It's something that has been added because it is convenient.

3 Likes

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.