是否有一个优雅的解决方案从另一个变异方法调用结构的变异方法?

时间:2018-01-23 18:44:58

标签: 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: 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.foo()无法编译:

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src\main.rs:15:14
   |
14 |         for (i, x) in self.a.iter_mut().enumerate() {
   |                       ------ first mutable borrow occurs here
15 |             *self.b_index_mut(i) += *x;
   |              ^^^^ second mutable borrow occurs here
16 |         }
   |         - first borrow ends here

这种可能的实现方法只需将S.b_index_mut()的主体移动到S.foo()即可消除此错误:

impl S {
    pub fn foo(&mut self) {
        for (i, x) in self.a.iter_mut().enumerate() {
            self.b[i] += *x;
        }
    }
}

然而,正如我在第一个实现中的评论中所说的那样,我想到的真正的S.b_index_mut()比例更加冗长,而且它确实应该有自己的功能。

可能的解决方法是将b作为参数传递给S.b_index_mut()

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;
        }
    }
}

此解决方案编译并解决抽象问题。但是,它似乎不够优雅。关于调用一个结构函数,我觉得有些不对,除了构造函数之外没有self

如果S.b_index_mut()的真实版本需要考虑S的更多成员(不是a),那么编写函数调用本身就会变得非常冗长。

这个问题有一个优雅的解决方案吗?

0 个答案:

没有答案
相关问题