我有一个由某些结构实现的特征.我想写一个模式匹配,我可以处理每个可能的情况:
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 …Run Code Online (Sandbox Code Playgroud) 场景.我正在写与游戏相关的代码.在那个游戏中Player(它也是一个类)有一个列表Item.还有其他类型的项继承Item,例如ContainerItem,DurableItem或WeaponItem.
显然,对我来说这是非常方便的List<Item>.但是当我获得玩家物品时,我唯一的方法是通过使用instanceof关键字来区分什么类型的物品.我敢肯定,我已经读过,依赖它是不好的做法.
在这种情况下可以使用它吗?或者我应该重新考虑我的所有结构?