在动态特征的实现中无法访问结构的字段 [英] Can't access fields of structs in implementations of dynamic traits

查看:61
本文介绍了在动态特征的实现中无法访问结构的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用通用参数实现特征并访问这些通用参数的字段时,我遇到一条错误消息,提示所涉及的参数不包含此类字段.

While trying to implement traits with generic arguments and access the fields of those generic arguments, I've encountered an error message saying that the arguments in question do not contain such fields.

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

Here's some example code that exhibits the issue:

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

(游乐场)

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

The error message given by the compiler is as follows:

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

在上下文中几乎没有意义.我希望这可能是我滥用通用特征的一部分,但是错误消息提出了这个问题.

which makes little sense in the context. I expect that this is probably some misuse of generic traits on my part but the error message makes the question that.

推荐答案

在方法实现的上下文中,Settings是通用类型".

Within the context of the method implimentation, Settings is a "generic type".

也就是说,您在示例中所获得的等同于此:

That is, what you've got there in your example, is the equivalent of this:

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

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

Does the error make more sense now? Your generic type Settings is shadowing your actual type Settings.

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

Your method isn't very generic in this sense now anyway.. since you're saying "I want an actual instance of a Settings struct". Whereas you probably want "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
}

游乐场链接

这篇关于在动态特征的实现中无法访问结构的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆