可以访问结构成员的 'TypeId' 吗?
Possible to access the 'TypeId' of a struct member?
有没有办法通过名称访问结构成员的 TypeId
(std::any::TypeId::of::<T>
)?
如果我有一个基本结构:
MyStruct {
value: i64,
}
而且我只知道 MyStruct
和 value
,有没有办法访问 TypeId::of::<i64>
- 其中 i64
取决于 value
的类型?
main () {
assert_eq!(
TypeId::of::<i64>,
// ^^^ this works
type_id_of!(MyStruct, value),
// ^^^ this is what I'm looking for
);
}
参见相关问题:Is it possible to access the type of a struct member for function signatures or declarations?
您可以使用类型检测来推断您拥有的值的任何字段的 TypeId
,只要它是 'static
(其他 TypeId::of
不起作用):
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));
}
然后,利用您提出的 问题中的策略,您可以制作一个宏来从没有实例的类型中获取它:
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));
}
有没有办法通过名称访问结构成员的 TypeId
(std::any::TypeId::of::<T>
)?
如果我有一个基本结构:
MyStruct {
value: i64,
}
而且我只知道 MyStruct
和 value
,有没有办法访问 TypeId::of::<i64>
- 其中 i64
取决于 value
的类型?
main () {
assert_eq!(
TypeId::of::<i64>,
// ^^^ this works
type_id_of!(MyStruct, value),
// ^^^ this is what I'm looking for
);
}
参见相关问题:Is it possible to access the type of a struct member for function signatures or declarations?
您可以使用类型检测来推断您拥有的值的任何字段的 TypeId
,只要它是 'static
(其他 TypeId::of
不起作用):
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));
}
然后,利用您提出的
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));
}