[英]What is an idiomatic way to have multiple structs with the same properties in Rust?
I'm aware that Rust does not have inheritance and that the language provides and easy way to share different implementations of the same methods across objects through the use of Traits.我知道 Rust 没有 inheritance 并且该语言提供了一种简单的方法来通过使用特征在对象之间共享相同方法的不同实现。 But is there an idiomatic way to share property name definitions or do they need to be defined on each struct?
但是是否有一种惯用的方式来共享属性名称定义,或者是否需要在每个结构上定义它们?
My use case is that I have many different structs that track some information.我的用例是我有许多不同的结构来跟踪一些信息。 Each piece of information can be updated and I want each struct to know the date of its last update.
每条信息都可以更新,我希望每个结构都知道其上次更新的日期。 Is there a common pattern (maybe macros?) to add a
last_update
property to all the structs or must I add it to each struct explicitly?是否有一个通用模式(可能是宏?)将
last_update
属性添加到所有结构,或者我必须将它显式添加到每个结构?
There is currently no way to do this via traits, the closest thing is the "Fields in Traits" RFC ( discussion , RFC ), but that doesn't seem terribly active as of now.目前还没有办法通过特征来做到这一点,最接近的是“特征中的字段”RFC(讨论, RFC ),但目前看来还不是很活跃。
The simplest way to do this is to have a type / struct with a method and include that field in any struct you want:最简单的方法是拥有一个带有方法的类型/结构,并将该字段包含在您想要的任何结构中:
struct UpdateTimestamp {
timestamp: Timestamp, // dummy type
}
impl UpdateTimestamp {
fn update(&mut self) {
self.timestamp = now(); // dummy function
}
fn last_updated(&self) -> Timestamp {
self.timestamp
}
}
You could then include this in any struct where you want the functionality:然后,您可以将其包含在您想要该功能的任何结构中:
struct MyStruct {
my_field: u32,
my_other_field: i32,
update_ts: UpdateTimestamp,
}
impl MyStruct {
fn my_field(&self) -> u32 {
// Getter - no update
self.my_field
}
fn set_my_field(&mut self, my_field: u32) {
self.update_ts.update();
self.my_field = my_field;
}
fn last_updated(&self) -> Timestamp {
self.update_ts.last_updated()
}
}
Now you could write a complicated macro for this which automates the implementation part (injects updates into the setters and the last_updated
method in the impl block), but unless you're doing this a lot I don't think it would be worth it.现在您可以为此编写一个复杂的宏来自动化实现部分(将更新注入到 setter 和 impl 块中的
last_updated
方法中),但除非您经常这样做,否则我认为这不值得。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.