我只是實現了一個簡單的特質,以保持一個結構屬性的歷史:我可以實現在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
),有效地加強了有關變量採用哪些值的一些信息?