Skip to content

assign_op_pattern suggested change is a compiler error for non-primitive vector elements #9180

@sigh

Description

@sigh

Summary

In the repro case below, the borrow checker disallows a direct use of the assign operator when attempting to add two elements of a vector. I'm not sure what the necessary requirements are on the vector element types, but a wrapped i32 suffices. If I split it out into the long form pattern, then clippy says to change it back even though that would be a compile error.

Specifically, in the repro below, clippy wants to change x[0] = x[0] + x[1]; to x[0] += x[1];, but that results in the following compiler error:

  --> src/main.rs:22:13
   |
22 |     x[0] += x[1];
   |     --------^---
   |     |       |
   |     |       immutable borrow occurs here
   |     mutable borrow occurs here
   |     mutable borrow later used here

Lint Name

assign_op_pattern

Reproducer

I tried this code:

use core::ops::{Add, AddAssign};

#[derive(Debug, Copy, Clone)]
struct Foo(i32);

impl AddAssign for Foo {
    fn add_assign(&mut self, other: Self) {
        self.0 += other.0;
    }
}

impl Add for Foo {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self(self.0+other.0)
    }
}

fn main() {
    let mut x = vec![Foo(1),Foo(2),Foo(3)];
    x[0] = x[0] + x[1];
    println!("{:?}", x[0]);
}

I saw this happen:

  --> src/main.rs:22:5
   |
22 |     x[0] = x[0] + x[1];
   |     ^^^^^^^^^^^^^^^^^^ help: replace it with: `x[0] += x[1]`
   |
   = note: `#[warn(clippy::assign_op_pattern)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assign_op_pattern

I expected to see this happen:

No lint warning.

Version

I ran the minimal case above in the rust playground, with "Stable version: 1.62.0". I'm not sure how to get it to say the full version info.

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions