rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.35k stars 1.53k forks source link

`partial_pub_fields`: disallow partial fields of a struct be pub #9604

Closed TennyZhuang closed 2 years ago

TennyZhuang commented 2 years ago

What it does

https://matklad.github.io//2022/05/29/binary-privacy.html

Most structs are either ADT or Data, they shouldn't have a non-empty subset of pub fields.

The rule can be default allowed, since it may break some public APIs.

For pub(crate) or pub(mod path), it's commonly used as a friend class alternative, so I think we can treat them as private. If there are some requirements, we can add an option strict_partial_pub_fields later.

We can also introduce partial_pub_variants lint for enums later.

The lint can't be fixed automatically, since we don't know a struct is ADT or Data.

Lint Name

partial_pub_fields

Category

restriction

Advantage

Drawbacks

Example

#[derive(Default)]
pub struct FileSet {
  pub files: HashMap<VfsPath, FileId>,
  paths: HashMap<FileId, VfsPath>,
}

Could be written as:

#[derive(Default)]
pub struct FileSet {
  files: HashMap<VfsPath, FileId>,
  paths: HashMap<FileId, VfsPath>,
}
pub struct Color {
    pub r,
    pub g,
    b,
}

Could be written as:

pub struct Color {
    pub r,
    pub g,
    pub b,
}
TennyZhuang commented 2 years ago

@rustbot claim