rust-lang / rust-lang/rust-clippy

FP unnecessary_struct_initialization, suggestion does not compile, causes move error

Open
#10,547 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive I-suggestion-causes-error
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

.

Lint Name

unnecessary_struct_initialization

Reproducer

I tried this code:

struct S(i32);

// We should evaluate `x[2]` and copy the value out *before* evaluating the LHS
// and changing its value.
fn _fun() {
    let mut x = &[S(0), S(1), S(2)][..];
    let y = &mut S(7);
    *{
        x = &[S(3), S(4), S(5)];
        &mut *y
    } = S { ..x[2] };
    assert_eq!(2, y.0);
    assert_eq!(5, x[2].0);
}

pub fn main() {}

I saw this happen:

warning: unnecessary struct building
  --> src/main.rs:11:9
   |
11 |     } = S { ..x[2] };
   |         ^^^^^^^^^^^^ help: replace with: `x[2]`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_struct_initialization
   = note: `#[warn(clippy::unnecessary_struct_initialization)]` on by default

The suggested code does not compile:

The following errors were reported:
error[E0508]: cannot move out of type `[S]`, a non-copy slice
  --> src/main.rs:11:9
   |
11 |     } = x[2];
   |         ^^^^
   |         |
   |         cannot move out of here
   |         move occurs because `x[_]` has type `S`, which does not implement the `Copy` trait

error: aborting due to previous error

For more information about this error, try `rustc --explain E0508`.
Original diagnostics will follow.
Version
rustc 1.70.0-nightly (8be3c2bda 2023-03-24)
binary: rustc
commit-hash: 8be3c2bda6b683f87b24714ba595e8b04faef54c
commit-date: 2023-03-24
host: x86_64-unknown-linux-gnu
release: 1.70.0-nightly
LLVM version: 15.0.7
Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the unnecessary_struct_initialization lint and the Rust reproducer in this issue. Check how its suggestion is generated; done means the suggested replacement compiles for the non-Copy slice case and preserves the demonstrated assertions.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.