rust 方块和弧形魔术

8dtrkrch  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(136)

在Rust中,您可以使用某种编译器魔术(通过as关键字访问)将Arc/Box/Rc<T>转换为Arc/Box/Rc<dyn Trait>,是否有办法为用户定义类型选择这种魔术,或者ArcBox是特殊情况?
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`.
xqkwcwgp

xqkwcwgp1#

可以,但只能在夜间使用(而且此功能无法稳定运行)。此功能通过CoerceUnsized运行:

#![feature(coerce_unsized, unsize)]

impl<T: ?Sized + std::marker::Unsize<U>, U: ?Sized> std::ops::CoerceUnsized<X<U>> for X<T> {}

相关问题