如何从函数中 return Any?

How to return Any from a function?

我正在为一个数据库项目开发类型系统。一个问题是将类型 ID 映射到给定类型 ID 和地址的 reader,函数可以 return 给定从 u32String 到内置的任何数据类型定义的结构。

我对writer没意见,喜欢这样的宏

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

但对于 reader Any 似乎不太适合用作 return 值,因为 the trait bound "std::any::Any + 'static: std::marker::Sized" is not satisfied。我也试过return作为参考,但是我卡在了一辈子

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

抱怨 missing lifetime specifier。如果 'static 由于 return 值不够长而不能在这里工作,我如何在这里指定生命周期?

PS。 $io returns 任意类型的读取函数。

Any 是一个特征,这意味着它没有大小,因此不能按原样由函数返回。

不过,你可以试试装箱:

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

一个例子playpen