Skip to content

Warn on useless bindings like let v2 = v1.sort(); #71432

Closed
@mbrubeck

Description

@mbrubeck

I've seen a lot of beginning Rust programmers make a mistake similar to the program below, which compiles and runs without warning:

fn main() {
    let mut x = [0,1,2];
    x[0] = 5;
    let y = x.sort();
    println!("{:?}", y);
}

The bug in this program is hard for new Rust programmers to spot. The compiler should help them, by warning that x.sort() does not return a value.

This could be done with a new attribute #[must_not_use], applied to functions like sort. This would be the inverse of must_use: It would warn only if the result of the function is used. Like must_use, it would take an optional argument that provides an additional diagnostic message.

(Bikeshed: must_not_use may be a confusing name. Other suggestions welcome.)

Or perhaps any assignment let foo = expr; where expr has type () should cause a warning by default. This would be a more general solution, catching more possible errors but also potentially causing more disruption. The warnings in this case might be less helpful, because they wouldn't include suggestions tailored to specific functions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions