trait FooTrait {}
struct FooStruct;
impl FooTrait for FooStruct {}
fn main() {
let maybe_struct: Option<dyn FooStruct> = None;
// Does not compile
let maybe_trait: Option<Box<dyn FooTrait>> = maybe_struct.map(Box::new);
// Compiles fine
let maybe_trait: Option<Box<dyn FooTrait>> = match maybe_struct {
Some(s) => Some(Box::new(s)),
None => None,
};
}
error[E0404]: expected trait, found struct `FooStruct`
--> src/main.rs:9:34
|
9 | let maybe_struct: Option<dyn FooStruct> = None;
| ^^^^^^^^^ not a trait
Rustc 1.23.0。为什么第一种方法不能编译?我是否遗漏了一些明显的东西,或者......嗯?