简体   繁体   中英

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

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>;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM