rust - 我可以在 Rust 中实现将信息添加到外部类型的特征吗?

标签 rust traits

我只是实现了一个简单的特征来保存结构属性的历史:

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 特征(或类似的东西)添加到还没有 history 属性的东西中吗(像 u32String), 有效地附加一些关于变量取值的信息?

最佳答案

没有。 Traits 不能将数据成员添加到现有结构中。实际上,只有程序员可以通过修改结构的定义来做到这一点。包装结构或哈希表是可行的方法。

关于rust - 我可以在 Rust 中实现将信息添加到外部类型的特征吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364211/

相关文章:

reference - 如何将具体类型的迭代器特征对象转换为特征对象的迭代器特征对象?

scala - 扩展内置集合,内置方法的问题

rust - 在Rust教程代码中获取 “error[E0599]: no method named write_fmt found”错误

generics - 为实现特征的所有类型实现特征

casting - 了解类型推断

rust - 尝试在 Rust 中实现 sscanf,在传递 &str 作为参数时失败

javascript - 使用传递给 Rust 的 JavaScript 对象时是否会影响性能?

windows - 检查文件是否是 Windows 上 Rust 2018 中的符号链接(symbolic link)

rust - 代码无需借用即可工作,但我无法通过借用使其工作

特征作为函数的返回值