如何从这段代码中的变量获取Box<B>or &Bor :&Box<B>``a
Box<B>
&B
&Box<B>``a
trait A {} struct B; impl A for B {} fn main() { let mut a: Box<dyn A> = Box::new(B); let b = a as Box<B>; }
此代码返回一个错误:
error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>` --> src/main.rs:8:13 | 8 | let b = a as Box<B>; | ^^^^^^^^^^^ | = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
您不能直接将 a 转换Box<dyn A>为 a,Box<B>因为 Rust 不允许这样的非原始转换。但是,您可以使用特征downcast提供的方法实现所需的目的Any,该方法允许将特征对象动态转换为具体类型。
Box<dyn A>
downcast
Any
以下是修改代码以实现所需行为的方法:
锈复制代码use std::any::Any; trait A {} struct B; impl A for B {} fn main() { let mut a: Box<dyn A> = Box::new(B); // Attempt to downcast the trait object to a concrete type let b = match a.downcast::<B>() { Ok(b) => b, Err(_) => panic!("Failed to downcast to B"), }; // Now `b` is a Box<B> let b: Box<B> = Box::new(*b); }
在此代码中:
a
B
b
Err