在Rust中,您可以使用某种编译器魔术(通过as
关键字访问)将Arc/Box/Rc<T>
转换为Arc/Box/Rc<dyn Trait>
,是否有办法为用户定义类型选择这种魔术,或者Arc
和Box
是特殊情况?
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=79c969fe9bdca1d20637c33436e55cda
use std::sync::Arc;
struct X<T: ?Sized> {
t: Box<T>,
}
impl <T> X<T> {
pub fn new(t: T) -> Self {
Self { t: Box::new(t) }
}
}
pub fn main() {
let x = Arc::new("123".to_owned()) as Arc<dyn AsRef<str>>;
let x = Box::new("123".to_owned()) as Box<dyn AsRef<str>>;
let x = X::new("123".to_owned()) as X<dyn AsRef<str>>;
}
错误:
error[E0605]: non-primitive cast: `X<String>` as `X<dyn AsRef<str>>`
--> src/main.rs:16:13
|
16 | let x = X::new("123".to_owned()) as X<dyn AsRef<str>>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
For more information about this error, try `rustc --explain E0605`.
1条答案
按热度按时间xqkwcwgp1#
可以,但只能在夜间使用(而且此功能无法稳定运行)。此功能通过
CoerceUnsized
运行: