types - Possible to access the 'TypeId' of a struct member? -


is there way access typeid (std::any::typeid::of::<t>) of struct member name?

if have basic struct:

mystruct {     value: i64, } 

and know mystruct , value, there way access typeid::of::<i64> - i64 depends on type of value?

main () {     assert_eq!(         typeid::of::<i64>,         // ^^^ works         type_id_of!(mystruct, value),         // ^^^ i'm looking     ); } 

see related question: is possible access type of struct member function signatures or declarations?

you can use type detection deduce typeid of field of value have, long it's 'static (other typeid::of doesn't work):

fn type_id<t: 'static + ?sized>(_: &t) -> typeid {     typeid::of::<t>() }  fn main() {     let m = mystruct { value: 4 };     println!("{:?} {:?}", typeid::of::<i64>(), type_id(&m.value)); } 

then, leveraging strategy in offsetof question asked, can make macro type without having instance:

macro_rules! type_id_of {     ($t:ty, $f:ident) => {         {             fn type_of<t: 'static + ?sized>(_: &t) -> typeid {                 typeid::of::<t>()             }             let base: $t = unsafe { ::std::mem::uninitialized() };             let result = type_of(&base.$f);             ::std::mem::forget(base);             result         }     } }  fn main() {     println!("{:?} {:?}", typeid::of::<i64>(), type_id_of!(mystruct, value)); } 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -