1个不稳定版本

0.1.0 2024年4月13日

#27 in #downcast


dyncast中使用

MIT/Apache

13KB
306

dyncast

github crates.io docs.rs

概念验证。

此库提供了对dyn Trait的opt-in类型下转型。

警告:此方法的正确性尚未验证。

use std::any::Any;

use dyncast::{dyncast, DyncastExt};

#[dyncast]
trait Boba {
    fn supper(&self);
}

struct A;

#[dyncast]
impl Boba for A {
    fn supper(&self) {
        println!("a")
    }
}

struct B;

#[dyncast]
impl Boba for B {
    fn supper(&self) {
        println!("b")
    }
}

#[dyncast]
trait Soba {}

#[test]
fn boba() {
    let a = A;
    let b = B;

    let a = &a as &dyn Any;
    let b = &b as &dyn Any;

    assert!(a.dyncast_to::<dyn Boba>().is_some());
    assert!(b.dyncast_to::<dyn Boba>().is_some());

    assert!(a.dyncast_to::<dyn Soba>().is_none());
    assert!(b.dyncast_to::<dyn Soba>().is_none());
}

平台支持

该crate已在以下平台上测试和验证

  • macOS x86_64, aarch64
  • Linux x86_64, aarch64
  • Windows 1X x86_64

依赖项

~290–740KB
~18K SLoC