Skip to content

New lint: prefer union field access to transmuting into an union #2361

@gnzlbg

Description

@gnzlbg

See it live:

This code

pub unsafe fn bad(a: [u32; 4], idx: usize) -> u64 {
    union A { _a: [u32; 4], b: [u64; 2] };
    ::std::mem::transmute::<[u32; 4], A>(a).b[idx]
}

should be more idiomatically be written as this:

pub unsafe fn better(a: [u32; 4], idx: usize) -> u64 {
    union A { a: [u32; 4], b: [u64; 2] };
    A { a: a }.b[idx]  // the a: a has been added for clarity, a suffices
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.L-guidelinesLint: Related to the Rust API GuidelinesL-unnecessaryLint: Warn about unnecessary codeT-middleType: Probably requires verifiying types

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions