rust-lang / rust-lang/rust-clippy
Function attribute to disallow unwrap of returned value
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
Sometimes you have a function where, if the caller unconditionally unwraps the returned value, there exists a better way to write that.
Advantage
- Encourages consistency.
- Encourages better panic error messages since you can write it once and re-use rather than re-writing `expect("shouldn't happen") N times.
Drawbacks
- People may be tempted to use the attribute for the wrong reason. It should not be used for "this is dangerous to unwrap" because that's rather subjective and that should be a decision left for the caller. Maybe there is a better attribute name?
Example
#[clippy::no_unwrap(reason = "use `get_foo` instead")]
fn try_get_foo() -> Option<Foo> {
...
}
fn get_foo() -> Option<Foo> {
try_get_foo().expect("really nice error message")
}
fn example() {
let x = try_get_foo().unwrap(); // LINT
}
Could be written as:
fn example() {
let x = get_foo();
}
Comparison with existing lints
No response
Additional Context
One tricky question: should it also lint on usages of .expect("...")? I think this would usually be good, but I'm afraid it may cause some false positives where the caller intentionally uses a different error message. So I think I would not want it to lint expect.
Clippy should error/warn on using the attribute for a function that does not return Option or Result.
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
No source files, tests, or entry points are named in the issue. Start by resolving the attribute name, whether expect should be linted, and how invalid return types are diagnosed. Done means the attribute can warn on unwrap for Option or Result, recommend the alternate function, and reject unsupported return types.
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
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100