Skip to content

Trivial cast warning for cast that can't be removed #23742

Closed
@bluss

Description

@bluss

The following code yields warnings:

warning: trivial cast: `&mut T` as `*mut T`, #[warn(trivial_casts)] on by default

Warning spots are marked // WARN below

#[warn(trivial_casts)]
enum Pair<T> {
    Both(T, T),
    One(T),
    None,
}

fn index_twice<T>(slc: &mut [T], a: usize, b: usize) -> Pair<&mut T>
{
    if a == b {
        slc.get_mut(a).map_or(Pair::None, Pair::One)
    } else {
        if a >= slc.len() || b >= slc.len() {
            Pair::None
        } else {
            // safe because a, b are in bounds and distinct
            unsafe {
                let ar = &mut *(slc.get_unchecked_mut(a) as *mut _); // WARN
                let br = &mut *(slc.get_unchecked_mut(b) as *mut _); // WARN
                Pair::Both(ar, br)
            }
        }
    }
}

The casts are non-trivial because without them the code does not pass the borrow check. Under the circumstances above we do so soundly by using an unsafe block.

Warning introduced in #23630

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions