rust-clippy
rust-clippy copied to clipboard
unnecessary call to max function
What it does
In todays AdventOfCode i caught myself using the below example.
The max()
call of an unsigned number with 0 is unnecessary.
It would be nice if clippy would say something about that.
the maximum between 0 and an unsigned number is always the number.
Please let me know if i did anything wrong. Have a nice day.
Advantage
- Remove of unnecessary function call
- Reduction of Code Complexity
Drawbacks
No response
Example
let x: usize = 5;
let y: usize = 8;
let ret = 0.max(x.saturating_sub(y));
Could be written as:
let x: usize = 5;
let y: usize = 8;
let ret = x.saturating_sub(y);
I would like to contribute in this issue if you don't mind. Though I'll take some time as I'm new to this community but I am highly interested.
Yeah feel free to do so. I’m new to this community and “public” GitHub too. I would love to see with what you come up with.
I pushed the wrong button and I don’t know how to fix it. Sorry
@rustbot claim
@FelixMaetzler so you meant to say that when you run the lint on
let x: usize = 5;
let y: usize = 8;
let ret = x.saturating_sub(y);
it changes to
let x: usize = 5;
let y: usize = 8;
let ret = 0.max(x.saturating_sub(y));
Am I going in the right direction?
Or do you mean that when someone runs cargo clippy
on
let x: usize = 5;
let y: usize = 8;
let ret = 0.max(x.saturating_sub(y));
should give an error/warning?
It should probably warn on 0.max(<anything>)
yes. One can just use the argument directly. 0.max(x + y)
is the same as x + y
for unsigned integer types
Or do you mean that when someone runs
cargo clippy
onlet x: usize = 5; let y: usize = 8; let ret = 0.max(x.saturating_sub(y));
should give an error/warning?
yes exactly that.
like @y21 said, you could generalize that to 0.max(<anything>)
can be replaced by <anything>
if <anything>
evaluates (or is) an unsigned integer.
the part with the saturating_sub()
was just my specific case, where i discovered that you don't need the max()
method.
In my opinion this should give a similar/same cargo clippy output like following:
let b = 12 + 0;
dbg!(b);
Gotcha!
@rustbot claim
Hi @lightlessdays, are you still working on this? Would you mind if I claim it?
Hi @lightlessdays, are you still working on this? Would you mind if I claim it?
Hey, I am sorry, I got busy with my university exams. Well... You can claim it I suppose. Really sorry about ghosting this issue. @vohoanglong0107
Thanks @lightlessdays. Then I will start working on this
@rustbot claim