Hi there,
I am quite new to Rust and currently just playing with a little project.
As I needed to implement the AddAssign Trait, I went to the docs and the example AddAssign in std::ops - Rust made me wondering why it is implemented like this
I suppose one advantage is that if you add a third field z to your point type, then the *self = Self { ... } version would not compile until you update it to also change the z field, whereas the self.x += other.x version would not remind you of this.
When manually implementing things like Debug or PartialEq I will destructure my type for exactly this reason. As long as you don't use .. the compiler will make sure you don't forget to update your code.
struct Point {
x: f32,
y: f32,
}
impl Debug for Point {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let Point { x, y } = self;
f.debug_struct("Point").field("x", x).field("y", y).finish()
}
}
The other thing I'd observe that's different is that if adding to each field is an operation that can panic, then assigning to self at the end prevents the possibility of the struct having an invalid state. This would probably only matter if you had a custom drop implementation.