特征的关联类型默认值
Associated type defaults on 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
它依赖于另一个关联类型的事实是无关紧要的。为关联类型提供默认值根本不是受支持的功能。
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
如果您想使用当前(不稳定的)实现,您可以使用 nightly 编译并启用 associated_type_defaults
功能,这对您的情况有效:
#![feature(associated_type_defaults)]
trait Foo {
type C;
type K = Vec<Self::C>;
}
我不确定我是否会推荐它,虽然只是基于跟踪问题表明不完整,但这取决于你。
综上所述,这不应该是“问题”。当然,提供默认值可能很方便,但这不是必需的。只需在实现特征时指定它:
trait Foo {
type C;
type K;
}
impl Foo for i32 {
type C = i32;
type K = Vec<Self::C>;
}
当我们需要一个依赖于特征中其他类型的类型时,我们如何克服关联类型默认值的问题?
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
它依赖于另一个关联类型的事实是无关紧要的。为关联类型提供默认值根本不是受支持的功能。
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
如果您想使用当前(不稳定的)实现,您可以使用 nightly 编译并启用 associated_type_defaults
功能,这对您的情况有效:
#![feature(associated_type_defaults)]
trait Foo {
type C;
type K = Vec<Self::C>;
}
我不确定我是否会推荐它,虽然只是基于跟踪问题表明不完整,但这取决于你。
综上所述,这不应该是“问题”。当然,提供默认值可能很方便,但这不是必需的。只需在实现特征时指定它:
trait Foo {
type C;
type K;
}
impl Foo for i32 {
type C = i32;
type K = Vec<Self::C>;
}