我有一个特质(Trait),它由一些结构体(Struct)实现。我想编写一个模式匹配(Pattern Match),以便可以处理每种可能的情况:
trait Base {}
struct Foo {
x: u32,
}
struct Bar {
y: u32,
}
impl Base for Foo {}
impl Base for Bar {}
fn test(v: bool) -> Box<Base + 'static> {
if v {
Box::new(Foo { x: 5 })
} else {
Box::new(Bar { y: 10 })
}
}
fn main() {
let f: Box<Base> = test(true);
match *f {
Foo { x } => println!("it was Foo: {}!", x),
Bar { y } => println!("it was Bar: {}!", y),
}
}
我遇到了这个编译错误:
error[E0308]: mismatched types
--> src/main.rs:25:9
|
25 | Foo { x } => println!("it was Foo: {}!", x),
| ^^^^^^^^^ expected trait Base, found struct `Foo`
|
= note: expected type `dyn Base`
found type `Foo`
error[E0308]: mismatched types
--> src/main.rs:26:9
|
26 | Bar { y } => println!("it was Bar: {}!", y),
| ^^^^^^^^^ expected trait Base, found struct `Bar`
|
= note: expected type `dyn Base`
found type `Bar`
struct Foo { f: uint }; enum FooBar { EFoo(Foo) }
。枚举还支持在其变体中添加字段(称为结构体变体):enum FooBar { Foo { f: uint } }
,尽管此功能是有条件的,这只是一种语法上的便利 - 结构体变体不是结构体,不能有方法。 - Vladimir MatveevAny
特质公开。AnyRefExt
有is::<T>()
方法,本质上与instanceof
相同。然而,Rust 不鼓励使用它,而是倡导静态类型检查。编写基于枚举的match
分发要安全得多,因为它保证处理每种可能的情况,并且可以在静态上检查。 - Vladimir Matveev