Skip to content

Simpler tuple <=> array conversions #10748

Closed

Description

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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