有没有办法检查结构体是否有字段并检查其类型?

Mad*_*Lee 2 rust

我正在尝试编写一个测试来确定是否struct A有一个属性a及其类型是i32.

pub struct A {
    a: i32,
}

#[test]
pub fn test_A() {
    assert!(A.hasattr("a"));
    assert_is_type!(A.a, i32);
}
Run Code Online (Sandbox Code Playgroud)

Loc*_*cke 6

在 Rust 中,与 Python 等某些语言不同,所有值的类型都必须在编译时已知。这个测试没有意义,因为为了编译代码,您必须已经知道答案。

如果结构体中的字段是可选的,请将其放入Option.

pub struct A {
    a: Option<i32>,
}
Run Code Online (Sandbox Code Playgroud)

如果多个结构之间有共同的功能,请为其创建一个特征。

pub trait ATrait {
    fn get_a(&self) -> i32;
}
Run Code Online (Sandbox Code Playgroud)