rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

New lint: map then unwrap

Open camsteffen opened this issue 3 years ago • 6 comments

What it does

Detects usage of map(..).unwrap()

Categories (optional)

Kind: pedantic

What is the advantage of the recommended code over the original code

The unwrap effectively only applies to the value before .map(..), so putting it after .map(..) needlessly complicates the semantics of the code.

Drawbacks

None.

Example

opt.map(|n| n * 2).unwrap()

Could be written as:

opt.unwrap() * 2

This should also work with expect as well as maybe other Option and Result transformers like filter.

I think the name map_unwrap is good, even though other method combinations are applicable.

camsteffen avatar Oct 04 '21 16:10 camsteffen

Hey, @camsteffen I did like to work on it although am new to this project so can you point me somewhere I can look at how to work this out. Thanks!

king-11 avatar Nov 20 '21 20:11 king-11

Hi @king-11! For lints that detect a sequence of method calls like this one, the implementation starts in the methods module. So you can start by adding a line for map right here (the methods are detected in reverse order): https://github.com/rust-lang/rust-clippy/blob/32048ebea3bfefd7bbe4d9f8e030a189c93122d5/clippy_lints/src/methods/mod.rs#L2315-L2319

Take a look at how some other lints in that file are implemented and that should give you good start. Feel free to drop questions on zulip.

camsteffen avatar Nov 20 '21 22:11 camsteffen

@rustbot claim

king-11 avatar Nov 21 '21 06:11 king-11

@camsteffen sorry for the long delay I was working on the code and now am writing some tests but am facing issue can you give me some sort of test case example that I can test with

king-11 avatar Sep 11 '22 10:09 king-11

What issue are you having trouble with? Feel free to ask it here or on zulip.

giraffate avatar Sep 15 '22 00:09 giraffate

I am not able to figure out how can I make a proper suggestion for this lint rule going from |n| n * 2 to just * 2

king-11 avatar Sep 15 '22 20:09 king-11