在 Rust 中,除了引用之外,
例如,
Box<T>
、Rc<T>
和 Arc<T>
也允许创建 trait 对象(例如,从 Box<Type>
到 Box<dyn Trait>
)。但是否有一种方法可以使用用户定义的通用“智能指针”类型进行相同的转换呢?例如,
MyBox<T>
是围绕 Box<T>
的薄包装器,但以下代码会导致编译错误:use std::io::Write;
pub fn main() {
let std_box: Box<Vec<u8>> = Box::new(Vec::new());
let std_dyn: Box<dyn Write> = std_box;
// ^ this conversion is allowed.
let my_box: MyBox<Vec<u8>> = MyBox { t: Box::new(Vec::new()) };
let my_dyn: MyBox<dyn Write> = my_box;
// ^ this conversion is not allowed.
}
struct MyBox<T: ?Sized> {
t: Box<T>,
}
error[E0308]: mismatched types
--> traits/src/trait_objs.rs:7:36
|
7 | let my_dyn: MyBox<dyn Write> = my_box;
| ---------------- ^^^^^^ expected trait object `dyn std::io::Write`, found struct `Vec`
| |
| expected due to this
|
= note: expected struct `MyBox<dyn std::io::Write>`
found struct `MyBox<Vec<u8>>`