rust - Is it possible to access the type of a struct member for function signatures or declarations? -
when defining implementations in macros, might useful access struct members type avoid having pass argument. (see this question)
impl partialeq<u32> mystruct { ... } is there way access type of struct member without knowing in advance type is?
impl partialeq<typeof(mystruct.member)> mystruct { ... } in case it's helpful, abbreviated example of why i'm interested this:
struct_bitflag_impl!( pub struct myflag(u8);, myflag, u8); // ^^ how avoid having arg? // (used ``impl partialeq<$t_internal> $p``) // couldn't discovered `myflag.0` ? // macro macro_rules! struct_bitflag_impl { ($struct_p_def: item, $p:ident, $t_internal:ty) => { #[derive(partialeq, eq, copy, clone, debug)] $struct_p_def impl ::std::ops::bitand $p { type output = $p; fn bitand(self, _rhs: $p) -> $p { $p(self.0 & _rhs.0) } } impl ::std::ops::bitor $p { type output = $p; fn bitor(self, _rhs: $p) -> $p { $p(self.0 | _rhs.0) } } impl ::std::ops::bitxor $p { type output = $p; fn bitxor(self, _rhs: $p) -> $p { $p(self.0 ^ _rhs.0) } } impl ::std::ops::not $p { type output = $p; fn not(self) -> $p { $p(!self.0) } } // support comparison base-type. impl partialeq<$t_internal> $p { fn eq(&self, other: &t_internal) -> bool { self.0 == *other } } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // how avoid using 't_internal' here? } }
no, general typeof(type::field) can used in type position not exist.
regarding example in question, looks expecting special kind of item: tuple-struct 1 field. so, instead of accepting $item fragment, can simulate syntax yourself:
macro_rules! foo { (pub struct $name:ident ( $ty:ident ) ) => { pub struct $name($ty); impl $name { pub fn bar() { println!("{}", stringify!($ty)); } } } } foo!( pub struct peter(u8) ); fn main() { peter::bar(); } that way have specify once. however, works 1 kind of tuple-struct definition, not kinds of items. use case suggests more or less interested in special case.
if want allow different kinds of struct definitions, need add more macro-rules macro allow different syntax. see example, here code allow pub , non-pub tuple-struct definitions. expanded more.
Comments
Post a Comment