#smart-pointers #downcast #traits #automatic #better #owned

better-as-any

Automatically makes your trait objects downcasting-capable

1 unstable release

new 0.1.0 Mar 21, 2025

#1186 in Rust patterns

45 downloads per month

MIT license

19KB
375 lines

Better As-Any

GitHub | Crates.io | Docs.rs

Overview

Better As-any is a refined implementation of the as-any crate. This crate avoids its predecessor's caveats that the API is error-prone when smart pointers are involved and it's impossible to downcasting an owned smart pointer.

With as-any crate, you can't directly call is or downcast* methods on a smart pointer, since it simply takes the smart pointer's reference and leads to a runtime error, which is hardly to be figure out.

Usage

Make your traits inherit the InheritAny trait, and all necessary functionalities will be added to your traits' implementors, including trait objects.

When downcasting is needed, corresponding helper traits including DowncastRef, DowncastMut and Downcast are expected to be imported.

use std::fmt::Debug;
use std::sync::Arc;

use better_as_any::{InheritAny, DowncastRef, Downcast};

pub trait Trait: InheritAny + Debug + Send + Sync {}

impl Trait for i32 {}

let val: Box<dyn Trait> = Box::new(42i32);
assert!(val.is::<i32>()); // No need to use `(*val).is::<i32>()`.

let val: Arc<dyn Trait> = Arc::from(val);
assert_eq!(*val.downcast_ref::<i32>().unwrap(), 42i32);
assert_eq!(val.downcast::<i32>().unwrap(), Arc::new(42i32)); // Downcasts the `Arc`.

No runtime deps