Mic*_*uza 6 traits rust type-alias
现有语法允许我们为关联类型编写默认值:
trait Foo {
type Bar = i32;
}
Run Code Online (Sandbox Code Playgroud)
我想要类似 C++ 的东西:
trait Foo {
typedef int Bar;
}
Run Code Online (Sandbox Code Playgroud)
这不是有效的 Rust 代码,但试图表明我的意图:
trait Foo<T> {
trait Trait = Into<T> + /* 10 other traits dependent on T */;
fn foo(x: Type) -> Trait;
}
Run Code Online (Sandbox Code Playgroud)
虽然特征别名目前不稳定,但您可以模拟它们。要创建“别名”,请定义一个新的空特征,并为满足您希望别名匹配的特征的所有类型编写一揽子实现。例如:
trait Short<T>: Into<T> /* plus others */ {}
impl<T, U> Short<T> for U where U: Into<T> /* plus others */ {}
Run Code Online (Sandbox Code Playgroud)
新特征的使用方式与使用别名的方式相同:
trait Foo<T> {
// Ret is bound by Into<T> and other bounds provided by Short
type Ret: Short<T>;
fn example(&self) -> Self::Ret;
}
struct X;
impl Foo<u32> for X {
type Ret = u8; // compiles because u8 is Into<u32>
fn example(&self) -> u8 {
0
}
}
Run Code Online (Sandbox Code Playgroud)