Rust 调用struct';另一种变异方法的变异方法是什么?
我有这样一个结构和方法:Rust 调用struct';另一种变异方法的变异方法是什么?,rust,Rust,我有这样一个结构和方法: pub struct S { a: Vec<u32>, b: Vec<u32>, } impl S { // Pretend that this function has a similar signature but an // implementation that is much more complicated and verbose fn b_index_mut(&mut self, i
pub struct S {
a: Vec<u32>,
b: Vec<u32>,
}
impl S {
// Pretend that this function has a similar signature but an
// implementation that is much more complicated and verbose
fn b_index_mut(&mut self, i: usize) -> &mut u32 {
&mut self.b[i]
}
pub fn foo(&mut self) {
for (i, x) in self.a.iter_mut().enumerate() {
*self.b_index_mut(i) += *x;
}
}
}
通过将S.b_index_mut()
的主体移动到S.foo()
,可以消除此错误:
然而,正如我在第一个实现的注释中所说的,我所想到的真正的S.b_index_mut()
比示例要详细得多,而且它确实应该有自己的功能
一种可能的解决方法是将b
作为参数传递给S.b_index_mut()
:
impl{
//假设此函数具有类似的签名,但
//实现更加复杂和冗长
fn b_index_mut(b:&mut Vec,i:usize)->&mut u32{
&mut b[i]
}
pub fn foo(&mut self){
对于self.a.iter_mut()枚举()中的(i,x){
*S::b_index_mut(&mut self.b,i)+=*x;
}
}
}
该解决方案编译并解决了抽象问题。然而,这似乎不雅。我觉得调用一个结构函数是不对的,除了构造函数之外,它不接受任何东西self
如果真正版本的S.b_index_mut()
需要分解S
的更多成员(它们不是a
),那么仅仅编写函数调用本身就可能变得非常冗长
这个问题有一个优雅的解决方案吗?。不管怎样,这就是你的“真实”抽象。
impl S {
pub fn foo(&mut self) {
for (i, x) in self.a.iter_mut().enumerate() {
self.b[i] += *x;
}
}
}
impl S {
// Pretend that this function has a similar signature but an
// implementation that is much more complicated and verbose
fn b_index_mut(b: &mut Vec<u32>, i: usize) -> &mut u32 {
&mut b[i]
}
pub fn foo(&mut self) {
for (i, x) in self.a.iter_mut().enumerate() {
*S::b_index_mut(&mut self.b, i) += *x;
}
}
}