是否可以从特征中访问结构字段? [英] Is it possible to access struct fields from within a trait?

查看:64
本文介绍了是否可以从特征中访问结构字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特质用于对要从结构体实现的某些功能进行分组,但是是否可以从特征中访问结构体字段?

Traits are used to group some functions to be implemented from a struct, but is it possible to access struct fields from within the trait?

我可以想象在特征中声明字段,以便字段也被抽象化.我还没有找到这样的语法;还有其他解决方案吗?否则,不可能有使用特征的非静态方法,对吗?

I could imagine declaring fields inside the trait so that the fields are abstracted as well. I haven't found such a syntax; is there any other solution? Otherwise, it wouldn't be possible to have non-static methods using a trait, would it?

我知道C#的面向对象编程,并且我正在研究Rust,以尝试适应C#中已经知道的OOP功能.

I know object oriented programming from C# and I'm playing around with Rust, trying to adapt the OOP functionality I already know from C#.

推荐答案

这听起来像是您误解了特质的工作原理.特质不能有田野.如果要提供从特征访问字段的权限,则需要在该特征中定义一个方法(例如get_blah).

This sounds like you're misunderstanding how traits work. Traits can't have fields. If you want to provide access to a field from a trait, you need to define a method in that trait (like, say, get_blah).

如果您要问是否可以从该结构的特征的实现中访问该结构的字段,则可以.该结构知道它是自己的类型,所以没有问题.

If you're asking whether you can access fields of a struct from within that struct's implementation of a trait, then yes. The struct knows it's own type, so there's no problem.

trait Pet {
    fn is_smelly(&self) -> bool;
}

struct Dog {
    washed_recently: bool,
}

impl Pet for Dog {
    fn is_smelly(&self) -> bool {
        !self.washed_recently
    }
}

如果您正在编写特征的 default 实现(在特征中定义方法主体),则否,您将无法访问字段.默认实现只能使用在特征或超级特征中定义的方法.

If you're writing a default implementation of a trait (i.e. defining a method body within the trait), then no, you can't access fields. A default implementation can only use methods that are defined on the trait or in a super trait.

这篇关于是否可以从特征中访问结构字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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