Any downcast for an array

I'm trying to write a function that takes a value that can be one of one of several types. I gave Any a try and it worked great... until I needed to accept a type that could be converted to a binary vector, Vec<u8>.

The function looks like:

fn my_func<T>(code: MyEnum, val: T) -> Result<()> 
where T: Any + 'static + Send
{
    let rval: &(dyn Any + 'static + Send) = &val;
    ...
}

The most convenient way to call it might be:
my_func(code, b"12345");

but the type for the byte string literal is &[u8 ; 5]

and so I'm trying to figure out how to match to that:

if let Some(v) = rval.downcast_ref<???>() { ... }

Thanks!

From std::array:

This should work if you stick to slices only:

fn my_func<T>(val: T) -> Result<(), ()> 
where T: Any + 'static + Send
{
    let rval: &(dyn Any + 'static + Send) = &val;
    
    if let Some(ref v) = rval.downcast_ref::<&[u8]>() {
        println!("v={:?}", v);
    }
    
    Ok(())
}

fn main() {
    my_func(&b"123"[..]);
}

If you are using nightly Rust, you might be able to solve this using the Unsize trait.

Yeah, I was afraid of that. It seems a simple enough solution, but it's for the public API of a library, and I'm sure there would be issues files for it being "broken"!

Another workaround would be doing something like stdlib, and providing 32 implementations ([T; 1] ... [T; 32])

First I thought that was a silly idea... then I implemented it! Oh, well. Good enough for now.

Thanks, @naim.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.