Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return Any from a function?

Tags:

rust

typing

I am working on type system for a database project. One problem is mapping a type id to a reader that given an type id and address, a function can return given any data type from built in u32, String, to defined structs.

I don't have any problem on writers, like such macro

    fn set_val (data: &Any, id:i32, mem_ptr: usize) {
         match id {
             $(
                 $id => $io::write(*data.downcast_ref::<$t>().unwrap(), mem_ptr),
             )*
             _ => (),
         }
    }

But for the reader Any seems not comfortable to be used as return value because the the trait bound "std::any::Any + 'static: std::marker::Sized" is not satisfied. I also tried to return as a reference, but I am stuck at a lifetime

    fn get_val (id:i32, mem_ptr: usize) -> Option<& Any> {
         match id {
             $(
                 $id => Some(&$io::read(mem_ptr)),
             )*
             _ => None,
         }
    }

which complains missing lifetime specifier. If 'static won't work here due to the return value not live long enough, how can I specify the lifetime here?

PS. The read function from $io returns any kinds of types.

like image 907
Shisoft Avatar asked Jan 06 '23 05:01

Shisoft


1 Answers

Any is a trait, which means that it is unsized and thus cannot be returned by a function as is.

However, you can try boxing it:

fn get_val (id:i32, mem_ptr: usize) -> Option<Box<Any>> {
     match id {
         $(
             $id => Some(Box::new($io::read(mem_ptr))),
         )*
         _ => None,
     }
}

An example playpen.

like image 106
Neikos Avatar answered Jan 13 '23 16:01

Neikos