Skip to content

Lint to warn when you are calling methods that can panic or send errors but don't return Result<T, U> or Option<T> #8184

@1Dragoon

Description

@1Dragoon

What it does

Some functions in Rust's standard library will panic if they're used incorrectly, and there isn't any warning against this.

Take for example:

let foo = Vec![1, 2, 3, 4, 5];
foo.swap_remove(8);

Since the index 8 is out of bounds, the code will panic and crash the program, instead of doing the more rusty thing of returning an Option so that we can handle it gracefully.

Similar thing occurs if you try to slice into a string:

let a = "ab早";
let a = &a[..3];

Another method with this problem is Vec::remove();

Since we probably can't change the API in a new edition of rust (or could we? older edition crates could have a .unwrap() inserted after to emulate the old behavior, so that no old crates break) I think a Clippy lint is the next best thing. I like how Rust basically garantees that your program won't crash unless you specifically say that it's ok to do so with .assert() or .unwrap(). Just need something like clippy to let us know when we run into those edge cases so we can avoid them (like unchecked .swap_remove() causing a panic,) so our beautiful applications can crash, making us look bad after we had just assured them that Rust solves all problems, including world hunger!

Lint Name

Warn Operation Panic Unchecked

Category

correctness, pedantic

Advantage

No unexpected application panic on older std methods that pre-dated Optionals.

Drawbacks

The lint could annoy you if you're already know about these pitfalls.

Example

Take for example:

let foo = Vec![1, 2, 3, 4, 5];
let bar = foo.swap_remove(8);
let quuz;
let foo = Vec![1, 2, 3, 4, 5];
let bar = if 8 < foo.len { Some(foo.swap_remove(8)); } else { None } // Note that this does an effective double bounds check, nothing can be done about that unless the rust devs change the way STD works.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions