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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With