[英]Why does using Option::map to Box::new a trait object not work?
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. Rustc 1.23.0。 Why doesn't the first approach compile?为什么第一种方法不能编译? Am I missing something obvious, or... huh?我是不是遗漏了一些明显的东西,或者……嗯?
Box::new
only works with sized types; Box::new
仅适用于大小类型; that is, it takes a value of a sized type T
and returns Box<T>
.也就是说,它接受一个大小为T
的值并返回Box<T>
。 In certain places a Box<T>
can be coerced into a Box<U>
(if T: Unsize<U>
).在某些地方, Box<T>
可以强制转换为Box<U>
(如果T: Unsize<U>
)。
Such coercion does not happen in .map(Box::new)
, but does in Some(Box::new(s))
;这种强制不会发生在.map(Box::new)
,但会发生在Some(Box::new(s))
; the latter is basically the same as Some(Box::new(s) as Box<FooTrait>)
.后者与Some(Box::new(s) as Box<FooTrait>)
基本相同。
You could create (in nightly) your own box constructor that returns boxes of unsized types like this:您可以(每晚)创建自己的盒子构造函数,它返回如下所示的未大小类型的盒子:
#![feature(unsize)]
fn box_new_unsized<T, U>(v: T) -> Box<U>
where
T: ::std::marker::Unsize<U>,
U: ?Sized,
{
Box::<T>::new(v)
}
and use it like .map(box_new_unsized)
.并像.map(box_new_unsized)
一样使用它。 See Playground .见游乐场。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.