UnbreakableROT26
UnbreakableROT26

Reputation: 73

Associated type defaults on trait

How can we overcome the problem of associated type defaults when we need a type that depends on other type in a trait?

    trait Foo{
        type C;
        type K = Vec<Self::C>;
    }
error[E0658]: associated type defaults are unstable
  |
3 |     type K = Vec<Self::C>;
  |     ^^^^^^^^^^^^^^^^^^^^^^
  |
   = note: see issue #29661 <https://github.com/rust-lang/rust/issues/29661> for more information

Upvotes: 7

Views: 6064

Answers (1)

kmdreko
kmdreko

Reputation: 60742

The fact that it depends on another associated type is irrelevant. Providing defaults for associated types is not yet a supported feature at all.

trait Foo {
    type K = i32;
}
error[E0658]: associated type defaults are unstable
 --> src/lib.rs:2:5
  |
2 |     type K = i32;
  |     ^^^^^^^^^^^^^
  |
  = note: see issue #29661 <https://github.com/rust-lang/rust/issues/29661> for more information

You can compile with nightly and enable the associated_type_defaults feature if you want to use the current (unstable) implementation, which does work for your case:

#![feature(associated_type_defaults)]

trait Foo {
    type C;
    type K = Vec<Self::C>;
}

I'm not sure I'd recommend it though just based on what the tracking issue indicates is incomplete, but that's up to you.


That all being said, this shouldn't be a "problem". Sure having defaults available could be convenient, but its not required. Just specify it when implementing the trait:

trait Foo {
    type C;
    type K;
}

impl Foo for i32 {
    type C = i32;
    type K = Vec<Self::C>;
}

Upvotes: 9

Related Questions