【问题标题】:Can't access fields of structs in implementations of dynamic traits [duplicate]在动态特征的实现中无法访问结构的字段[重复]
【发布时间】:2017-05-07 15:30:03
【问题描述】:

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

以下是一些显示该问题的示例代码:

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`

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

【问题讨论】:

    标签: generics rust traits


    【解决方案1】:

    在方法实现的上下文中,Settings 是“通用类型”。

    也就是说,您在示例中得到的内容与此等价:

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

    这个错误现在更有意义了吗?您的泛型类型 Settings 正在遮蔽您的实际类型 Settings

    无论如何,从这个意义上说,您的方法现在不是很通用.. 因为您说“我想要一个 Settings 结构的实际实例”。而您可能想要“我想要一个具有time 字段的任何类型的实例”。

    这是后者的做法:

    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

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多