Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 调用struct';另一种变异方法的变异方法是什么?_Rust - Fatal编程技术网

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