锈
做
允许借钱
部分
一个
struct
单独调用,但当调用一个函数/方法时
&mut Self
,这总是借用整个
结构
函数体永远不会用作附加信息。所以,解决问题的一个方法是重写函数签名,使其
做
掌握必要的信息。
impl Adder {
/// Algorithm implementation; takes all components explicitly.
/// Is not a method.
fn add_impl(current_value: &mut String, add_value: &str) {
current_value.push_str(add_value);
}
/// Method for external use â less flexible, but simple.
pub fn add(&mut self, value: &str) {
Self::add_impl(&mut self.current_value, value);
}
fn do_something(&mut self) {
Self::add_impl(&mut self.current_value, &self.first_step);
}
}
您的描述——一个可以用一些“常量”值更新自身的数据结构,这些值是在创建结构本身时定义的——表明您可能面临比这个简单示例更复杂的情况。如果您有多个需要更新的可变字段(或者即使您真的想使用方法语法),您可以进行另一个
结构
它包含正确的字段子集,然后是
do_something
可以称之为普通
&mut self
内部结构上的方法。
struct FancyAdder {
first_step: String,
data: AdderData,
}
struct AdderData {
current_value: String,
...
}
impl FancyAdder {
fn do_something(&mut self) {
// This borrows `self.data` mutably and `self.first_step` immutably.
// No overlap.
self.data.add(&self.first_step);
}
}
impl AdderData {
fn add(&mut self, value: &str) {
self.current_value.push_str(value);
}
}