Cursed Pattern for specialization

⚓ Rust    📅 2026-03-24    👤 surdeus    👁️ 1      

surdeus

i found myself in need of specialization for a function and ended up discovering this pattern

use std::any::{Any,TypeId};
pub trait SomeTrait:Sized+'static{
    fn do_stuff(myself:Self)->i32{
        let dyn_self:&dyn Any=&myself;
        if TypeId::of::<Self>()==TypeId::of::<i32>(){
            return *(dyn_self.downcast_ref()).unwrap()
        }
        if TypeId::of::<Self>()==TypeId::of::<u32>(){
            return *(dyn_self.downcast_ref::<u32>()).unwrap() as i32
        }
        non_specialized_impl(self)
    }
}
impl SomeTrait for i32{
}
impl SomeTrait for u32{
}

which thanks to const folding is actually zero cost. not much else to say, probably something to avoid in general but i thought it might still amuse you all

2 posts - 2 participants

Read full topic

🏷️ Rust_feed