rust-lang / rust-lang/rust-clippy
Bypassing constructor with manual_non_exhaustive and update syntax
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
When using a private zero sized field it prevents the update syntax { ..x } from working, but the non_exhaustive attribute does not.
Lint Name
manual_non_exhaustive
Reproducer
I tried this code:
mod foo {
#[non_exhaustive]
pub struct Person {
pub name: String,
pub age: u8,
// _private: (),
}
impl Person {
pub fn new(age: u8, name: String) -> Person {
assert!(age >= 18, "Can not create instance");
Person {
age,
name,
// _private: (),
}
}
}
}
use foo::Person; // imagine foo is an external crate
fn main() {
let p = Person::new(18, String::from("Peter"));
let p2 = Person { age: 10, ..p };
}
p2 can be constructed, although the constructor forbids it by having an assert.
If we use the _private: () field, we get an error like this:
error[E0451]: field `_private` of struct `Person` is private
--> src/main.rs:25:34
|
25 | let p2 = Person { age: 10, ..p };
| ^ field `_private` is private
So the question is, is this a case for #[allow(clippy::manual_non_exhaustive )] or should we check for possible side effects in the constructor? (please no! 🙈)
Version
rustc 1.76.0-nightly (a57770440 2023-11-16)
binary: rustc
commit-hash: a57770440f1ebe5b992551d3bcc489ae211908d4
commit-date: 2023-11-16
host: x86_64-unknown-linux-gnu
release: 1.76.0-nightly
LLVM version: 17.0.5
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the Rust example in the issue and inspect the manual_non_exhaustive lint. Determine the intended behavior for struct update syntax with #[non_exhaustive], then add or update a regression test showing the agreed behavior. Done means the lint handles this case consistently without analyzing constructor side effects.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100