可以访问结构成员的'TypeId'吗?

时间:2017-02-08 11:14:24

标签: types rust introspection

有没有办法按名称访问结构成员的TypeIdstd::any::TypeId::of::<T>)?

如果我有一个基本结构:

MyStruct {
    value: i64,
}

我只知道MyStructvalue,是否有办法访问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?

1 个答案:

答案 0 :(得分:5)

您可以使用类型检测推断出您所拥有的任何字段的import datetime from bson.json_util import dumps from bson.objectid import ObjectId #transform string to list result = eval(result) result_dict = dict(result) dumps(result_dict) Out[79]: '{"profileDetails": {"basicDetails": {"dateOfBirth": {"$date": 696902400000}, "customerCode": "C037799"}, "xDirLevel": {"masterCode": 1}}, "_id": {"$oid": "58872e99321a0c8633291b3f"}}' ,只要它TypeId(其他'static没有工作):

TypeId::of

然后,利用您提出的offsetof问题中的策略,您可以创建一个宏来从类型中获取它而不需要实例:

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));
}