Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clippy::restriction::pub_fields #13956

Open
onkoe opened this issue Jan 7, 2025 · 0 comments
Open

clippy::restriction::pub_fields #13956

onkoe opened this issue Jan 7, 2025 · 0 comments
Labels
A-lint Area: New lints

Comments

@onkoe
Copy link

onkoe commented Jan 7, 2025

What it does

Checks for pub fields on a type.

Advantage

For some uses, pub fields are disadvantageous and error-prone. Selectively adding #[deny(pub_fields)] to a type would make these uses more distinct.

Other advantages come from using private fields, which may include:

  • Preventing external mutation of internal invariants
  • (doubly so for unsafe)
  • Easier debugging and refactoring due to encapsulated logic

In short, all field accesses are within the type itself.

Drawbacks

There are no drawbacks past making code somewhat more verbose (lint, getters, setters, etc.), but that stems from private fields in general.

Newer programmers may accidentally apply it when they may not wish to do so. I strongly suggest asking users to apply this lint on a 'per-type' basis.

Example

Let's say that MyStruct is a large type with a huuuge impl block and lots of unsafe code.

Watching field accesses is vital to maintain memory safety in this type, so pub fields are generally unwanted.

// note: dear future contributors...
// please do not use `pub` fields in this type. encapsulation is
// important for safety, and blah blah blah...
pub struct MyStruct {
    some_fields: *mut (),
    // ...

    // let's say a contributor was loose with the rules. can also
    // occur with limited docs or in large projects!
    pub another_field: u32,
}

Could be written as:

#[deny(pub_fields, reason = "encapsulate safety invariants for fields")]
pub struct MyStruct {
    some_fields: *mut (),
    // ...
    another_field: u32,
}

The lint prevented potential changes that could affect memory safety. For example, another_field could be a computed offset that shouldn't be affected.

@onkoe onkoe added the A-lint Area: New lints label Jan 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

1 participant