Rust Any Part 3: Finally we have Upcasts
文章介绍了Rust中的As-Any Hack及其在早期版本中的局限性。随着Rust 1.86的发布,该问题已得到解决,允许将dyn DebugAny转换为dyn Any,并支持使用Any的方法。这使得许多旧的hack可以被淘汰。 2025-3-27 00:0:0 Author: lucumr.pocoo.org(查看原文) 阅读量:5 收藏

written on Thursday, March 27, 2025

Three years ago I shared the As-Any Hack on this blog. That hack is a way on stable rust to get upcasting to supertraits working in Rust. To refresh your memory, the goal was to make something like this work:

#[derive(Debug)]
struct AnyBox(Box<dyn DebugAny>);

trait DebugAny: Any + Debug {}

impl<T: Any + Debug + 'static> DebugAny for T {}

The problem? Even though DebugAny inherits from Any, Rust wouldn't let you use methods from Any on a dyn DebugAny. So while you could call DebugAny methods just fine, trying to use downcast_ref from Any (the reason to use Any in the first place) would fail:

fn main() {
    let any_box = AnyBox(Box::new(42i32));
    dbg!(any_box.0.downcast_ref::<i32>());  // Compile error
}

The same would happen if we tried to cast it into an &dyn Any? A compile error again:

fn main() {
    let any_box = AnyBox(Box::new(42i32));
    let any = &*any_box.0 as &dyn Any;
    dbg!(any.downcast_ref::<i32>());
}

But there is good news! As of Rust 1.86, this is finally fixed. The cast now works:

[src/main.rs:14:5] any.downcast_ref::<i32>() = Some(
    42,
)

At the time of writing, this fix is in the beta channel, but stable release is just around the corner. That means a lot of old hacks can finally be retired. At least once your MSRV moves up.

Thank you so much to everyone who worked on this to make it work!

This entry was tagged rust


文章来源: http://lucumr.pocoo.org/2025/3/27/any-upcast
如有侵权请联系:admin#unsafe.sh