【发布时间】:2019-02-25 16:14:49
【问题描述】:
当特征需要的状态多于结构中包含的状态时,如何为结构实现特征?例如,我将如何为下面显示的 Human 结构实现 Employee 特征?
struct Human {
name: &str,
}
trait Employee {
fn id(&self) -> i32;
fn name(&self) -> &str;
}
impl Employee for Human {
fn id(&self) -> i32 {
// From where do I get the ID?
}
fn name(&self) -> &str {
self.name
}
}
我没有看到任何方法可以将其他状态添加到 impl 或特征中。
是否只有创建一个新的 HumanToEmployeeAdapter 结构来保存缺失的信息,然后为新结构实现 Employee 特征?
附:我的背景是 C#。以下是我用那种语言处理它的方法:
class Human
{
public string Name { get; }
public Human(string name) { Name = name; }
}
interface IEmployee
{
int Id { get; }
string Name { get; }
}
class HumanToEmployeeAdapter : IEmployee
{
readonly Human _human;
public int Id { get; }
public string Name => _human.Name;
public HumanToEmployeeAdapter(
Human human,
int id)
{
_human = human;
Id = id;
}
}
您会注意到这是“创建一个新的HumanToEmployeeAdapter struct”路径。那么,这就是 Rustaceans 解决这个问题的方式吗?
【问题讨论】:
-
你的背景是C#,所以如果你用
GetId方法实现了一个C#接口,在这种情况下你会如何提供呢? -
“当 trait 需要的状态多于结构中包含的状态时,我如何为结构实现 trait” => 你不能。这不是特征的用途。您需要创建另一个结构(可能是包装器类型)。
-
提示:rust 不会归类为 OO。
-
评论不是进入这个论点的最佳位置,但我们中的许多人(包括我自己)将 Rust 视为一种 OO 语言。它没有继承,但这不是 OO 所必需的。
标签: oop struct rust traits composition