Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simpler tuple <=> array conversions #10748

Closed
leonardo-m opened this issue May 5, 2023 · 0 comments · Fixed by #11020
Closed

Simpler tuple <=> array conversions #10748

leonardo-m opened this issue May 5, 2023 · 0 comments · Fixed by #11020
Labels
A-lint Area: New lints

Comments

@leonardo-m
Copy link

What it does

It suggests better code in cases of conversions from/to tuples to/from arrays.

Lint Name

simple_tuple_array_conversion

Category

style

Advantage

The code is simpler, shorter, less bug-prone.

Since this the array <=> tuple conversions are allowed:
rust-lang/rust#97594

Drawbacks

None.

Example

#![allow(unused_variables)]
fn main() {
    let t1: &[(u32, u32)] = &[(1, 2), (3, 4)];
    let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect();
    let t2: Vec<(u32, u32)> = v1.iter().map(|&[a, b]| (a, b)).collect();
}

Could be written as:

#![allow(unused_variables)]
fn main() {
    let t1: &[(u32, u32)] = &[(1, 2), (3, 4)];
    let v2: Vec<[u32; 2]> = t1.iter().map(|&t| t.into()).collect();
    let t3: Vec<(u32, u32)> = v2.iter().map(|&v| v.into()).collect();
}

The lint should work with longer arrays/tuples too. There are many more complex situations where the .into() could be used to convert between arrays and tuples, but I think this basic case is enough to keep lint logic simple, and it's enough to teach the programmer this transformation is allowed (Clippy is also a teaching tool).

@leonardo-m leonardo-m added the A-lint Area: New lints label May 5, 2023
bors added a commit that referenced this issue Jun 24, 2023
New lint [`tuple_array_conversions`]

Closes #10748

PS, the implementation is a bit ugly 😅 ~~I will likely refactor soon enough :)~~ Done :D

changelog: New lint [`tuple_array_conversions`]
@bors bors closed this as completed in c7bf05c Jul 1, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant