无法访问动态特征实现中的结构字段

Can't access fields of structs in implementations of dynamic traits

在尝试使用通用参数实现特征并访问这些通用参数的字段时,我遇到了一条错误消息,指出相关参数不包含此类字段。

下面是一些展示问题的示例代码:

pub struct Settings {
    pub time: String,
}

pub trait Foo {
    fn get<T>(t: T);
}

struct Bar;

impl Foo for Bar {
    fn get<Settings>(t: Settings) {
        let x = t.time;
    }
}

(Playground)

编译器给出的错误信息如下:

error: no field `time` on type `Settings`

这在上下文中没有什么意义。我认为这可能是我对通用特征的一些误用,但错误消息提出了这样的问题。

在方法实现的上下文中,Settings 是 "generic type"。

也就是说,您在示例中得到的内容等同于:

impl Foo for Bar {
    fn get<RandomWordHere>(t: RandomWordHere) {
        let x = t.time;
    }
}

错误现在更有意义了吗?您的通用类型 Settings 正在掩盖您的实际类型 Settings.

无论如何,从这个意义上说,您的方法现在不是很通用.. 因为您说的是 "I want an actual instance of a Settings struct"。而你可能想要 "I want an instance of any type that has a time field".

这是你如何做后者:

pub trait HasTime {
    fn get_time(&self) -> &String;
}

pub struct Settings {
    pub time: String
}

impl HasTime for Settings {
    fn get_time(&self) -> &String {
        &self.time
    }
}

pub struct OtherStruct;

pub trait Foo {
    fn get<T>(t: T) where T: HasTime;
}

struct Bar;

impl Foo for Bar {
    fn get<T>(t: T) where T: HasTime {
        let x = t.get_time();
    }
}

fn main() {
    Bar::get(Settings{time: "".into()}); // This is fine
    // Bar::get(OtherStruct{}); // This is an error.. it doesn't implement HasTime
}

Playground link