rust-lang / rust-lang/rust-clippy

New lint: warn againt matching on all-private struct

Open
#8,333 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

Firstly a disclaimer: I think this belongs to the compiler rather than clippy but putting it into clippy first is probably a good first step as it could allow experimentation with minimal annoyance. Feel free to close if you disagree.

When the code matches on a struct with all fields private or an empty struct with #[non_exhaustive] attribute using Foo { .. } syntax clippy warns against this because it breaks future-proofing of the type which library authors may not be aware of.
Disussion: https://internals.rust-lang.org/t/disallow-matching-on-all-private-structs/15993

Lint Name

match_fully_private_struct

Category

suspicious

Advantage

The code will not break if the library changes the type from struct to enum.

Drawbacks
  • Can FP on v @ Foo { .. }, but perhaps there's a way to improve the code here too? It could be also whitelisted.
  • A crate author might have meant to commit to the type staying a struct. Maybe this could be mitigated by having an attribute on the struct definition to (dis)allow it. (Is such thing possible in clippy?)
Example
mod foo {
    pub struct Foo {
        value: u8,
    }

    pub fn create() -> Foo {
        Foo { value: 42 }
    }
}

fn main() {
    let foo::Foo { .. } = foo::create();
}

Could be written as:

// mod foo omitted for brevity since it's the same as above

fn main() {
    let _: foo::Foo = foo::create();
}

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

The issue names no implementation files or tests. Start by reviewing the linked discussion and the match_fully_private_struct proposal, then use the examples to define the lint’s scope and handling of false positives. Done means the agreed behavior is implemented and covered for private and #[non_exhaustive] structs.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.