rust-clippy
rust-clippy copied to clipboard
New lint: suggest using "implicit named arguments"
What it does
This lint suggests using the feature added in the 1.58 version of Rust: implicit named arguments for formatting macros.
Lint Name
implicit_named_arguments
Category
style
Advantage
- Slightly less verbose code.
- (Arguably) less error prone code.
Drawbacks
The only drawback that I can see is that not everyone would probably be happy with this lint, so perhaps it should be opt-in (pedantic).
Example
println!("1 = {}, 2 = {}, 3 = {}", first, second, third);
Could be written as:
println!("1 = {first}, 2 = {second}, 3 = {third}");
Perhaps this issue duplicated https://github.com/rust-lang/rust-clippy/issues/633.
added in the 1.18 version of Rust
I think this should say 1.58, rather than 1.18: https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1580-2022-01-13
Initially I made a suggestion for this in https://github.com/rust-lang/rustfmt/issues/5450 , but it seems clippy would be a better target. I do think that this issue should be expanded to cover all cases listed below. My adjusted original post:
Since 1.58 Rust allows captured identifiers in format calls, i.e.
println!("Hello, {person}!");style strings (documentations). I would like to proposecargo clippyto automatically convertprintln!("Hello, {}!", person);and otherformat!-like calls to the inlined versions.
| Original code | After cargo clippy |
Notes |
|---|---|---|
println!("{}", a) |
println!("{a}") |
positional in-lining |
println!("{a}", a=b) |
println!("{b}") |
named param |
println!("{a:0$}", width) |
println!("{a:width$}") |
width param |
println!("{a:.0$}", prec) |
println!("{a:.prec$}") |
precision param |
I began av implementation of this lint based on the PR https://github.com/rust-lang/rust-clippy/pull/8518 by @Alexendoo. See first pass at https://github.com/nyurik/rust-clippy/commit/99f3352de82fca963e2fd97ceaad5544269de508. So far I got it to identify most cases, but I am still struggling with the internal API -- for some reason the suggestions do not modify the source code. I am also not certain how to parse the structs in case the same value is used multiple times, i.e. ("{0} {0}", var) case. Any help and feedback is greatly appreciated :)
You could do the same as in check_literal, using a map to only consider arguments that are used once
https://github.com/rust-lang/rust-clippy/blob/818a91e8c83b5acd040594bb03199966f6394f1a/clippy_lints/src/write.rs#L423-L430
I added some more implementation code, and some of it even works (kinda). Any feedback is welcome - probably best to do it on the #9233 PR. Thanks!
Forgot to comment on this one... DONE! :D