#![feature(const_type_id)] use std::any::{Any, TypeId}; use xreflect::{Reflect, ReflectError, StructReflect, StructType}; struct Test { a: i32, b: T, } impl Reflect for Test { fn amount_of_fields(&self) -> usize { 2 } fn try_get_index_of_field(&self, field_name: &str) -> Result { match field_name { "a" => Ok(0), "b" => Ok(1), _ => Err(ReflectError::FieldNotFound), } } fn try_get_field_at(&self, field_index: usize) -> Result<&T, ReflectError> { match field_index { 0 => (&self.a as &dyn Any) .downcast_ref::() .ok_or(ReflectError::WrongType), 1 => (&self.b as &dyn Any) .downcast_ref::() .ok_or(ReflectError::WrongType), _ => Err(ReflectError::FieldNotFound), } } fn try_get_field_mut_at( &mut self, field_index: usize, ) -> Result<&mut T, ReflectError> { match field_index { 0 => (&mut self.a as &mut dyn Any) .downcast_mut::() .ok_or(ReflectError::WrongType), 1 => (&mut self.b as &mut dyn Any) .downcast_mut::() .ok_or(ReflectError::WrongType), _ => Err(ReflectError::FieldNotFound), } } fn try_get_type_of_field_at(&self, field_index: usize) -> Result { match field_index { 0 => Ok(TypeId::of::()), 1 => Ok(TypeId::of::()), _ => Err(ReflectError::FieldNotFound), } } } impl StructReflect for Test { const TYPE: StructType = StructType::Record(&[("a", TypeId::of::()), ("b", TypeId::of::())]); const FIELD_NAMES: &'static [&'static str] = &["a", "b"]; fn try_get_index_of_field(field_name: &str) -> Result { match field_name { "aaa" => Ok(0), "b" => Ok(1), _ => Err(ReflectError::FieldNotFound), } } } mod __xreflect_builders0x121839438923924398234898924 { use xreflect_core::Builder; use crate::Test; pub(crate) struct TestBuilder { a: Option, b: Option, } impl Builder> for TestBuilder { fn with_field(mut self, field_name: &'static str, field_value: T) -> Self { match field_name { "a" => { if std::any::TypeId::of::() == std::any::TypeId::of::() { self.a = Some(unsafe { std::mem::transmute_copy::(&field_value) }); } else { panic!("Wrong type") } } "b" => { if std::any::TypeId::of::() == std::any::TypeId::of::() { self.b = Some(unsafe { std::mem::transmute_copy::(&field_value) }); } else { panic!("Wrong type") } } _ => panic!("Field not found"), } self } fn with_field_at(mut self, field_index: usize, field_value: T) -> Self { match field_index { 0 => { if std::any::TypeId::of::() == std::any::TypeId::of::() { self.a = Some(unsafe { std::mem::transmute_copy::(&field_value) }); } else { panic!("Wrong type") } } 1 => { if std::any::TypeId::of::() == std::any::TypeId::of::() { self.b = Some(unsafe { std::mem::transmute_copy::(&field_value) }); } else { panic!("Wrong type") } } _ => panic!("Field not found"), } self } fn try_build(self) -> Result, ()> { let Some(a) = self.a else { return Err(()) }; let Some(b) = self.b else { return Err(()) }; Ok(Test { a, b }) } } } #[test] fn main() { let a = Test { a: 32i32, b: 8u8 }; let b = a.get_field::("b"); dbg!(b); }