Skip to content

Lint: useless assignments to Copy temporaries #7117

Open
@michaelsproul

Description

@michaelsproul

What it does

Detect assignments to Copy values that are immediately discarded.

rustc is pretty good at detecting when variables are assigned but never read, and Clippy has a temporary_assignments lint to catch assignments to temporaries, but neither of them catch the following case:

struct Point { x: u64, y: u64 }

fn new_point() -> Point {
    Point {
        x: 10,
        y: 30,
    }
}

fn main() {
    new_point().x = 11;
}

Whether or not new_point has side-effects should be irrelevant: assigning to its .x field and then immediately throwing it away is definitely pointless (no pun intended 😏). Things are more complicated if Point has a drop implementation, hence the lint should probably be restricted to types that implement Copy.

Categories

  • Kind: correctness

Drawbacks

Potentially difficult to implement

Example

This example is more similar to the one I encountered in the real world: a Copy type with a mutable getter and a copying getter, where the copying getter is called by mistake:

#[derive(Debug, Clone, Copy)]
struct Point { x: u64, y: u64 }

#[derive(Debug)]
struct Container {
    point: Point,
}

impl Container {
    fn get_point(&self) -> Point {
        self.point
    }
    
    #[allow(unused)]
    fn get_point_mut(&mut self) -> &mut Point {
        &mut self.point
    }
}

fn main() {
    let container = Container {
        point: Point { x: 10, y: 30 },
    };
    container.get_point().x = 0; // oops! I meant `get_point_mut`!
    println!("{:?}", container);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions