linbuxiao / gitblog

1 stars 0 forks source link

Rust Struct Self Ref #11

Open linbuxiao opened 2 years ago

linbuxiao commented 2 years ago

困惑

这是一个写法和使用的困惑:当 impl struct 时,method 的首个参数可以为 self,也可以为 &self。 且当我们使用 &self 作为参数时,我们也可以调用 self。但这时 self 与参数类型为 &self 是不同的。 例如:

fn bar(mut self, i: &usize) {
    self.a = i;
}

此时 self 并不是一个引用,在执行 self.a = i 后,self 被 move 到了 fn bar 内,并且没有返回出去。 所以在 bar 的下文中再次调用 self 的 struct 会报错,因为 self 已经被 drop 了。 我们可以修改为

fn bar(&mut self, i: &usize) {
    self.a = i;
}

此时我们调用的仍然是 self 关键字,这里的 self 已经标为了 self 的引用。

linbuxiao commented 2 years ago

一句话总结:在函数参数中,冒号左边的部分,如:mut c,这个 mut 是对🪄函数体内部有效🪄;冒号右边的部分,如:&mut String,这个 &mut 是针对🪄外部实参传入时的形式(声明)说明🪄。