rust-lang / rust-lang/rust-clippy

Function attribute to disallow unwrap of returned value

Open
#17,335 0 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

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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.