我只是实现了一个简单的特质,以保持一个结构属性的历史:我可以实现在Rust中向外部类型添加信息的特性吗?
fn main() {
let mut weight = Weight::new(2);
weight.set(3);
weight.set(5);
println!("Current weight: {}. History: {:?}", weight.value, weight.history);
}
trait History<T: Copy> {
fn set(&mut self, value: T);
fn history(&self) -> &Vec<T>;
}
impl History<u32> for Weight {
fn set(&mut self, value: u32) {
self.history.push(self.value);
self.value = value;
}
fn history(&self) -> &Vec<u32> {
&self.history
}
}
pub struct Weight {
value: u32,
history: Vec<u32>,
}
impl Weight {
fn new(value: u32) -> Weight {
Weight {
value,
history: Vec::new(),
}
}
}
我不认为这是可能的,但你可以在History
特征(或等价的东西)添加到一些东西,没有按” t已经有一个history
属性(如u32
或String
),有效地加强了有关变量采用哪些值的一些信息?