Skip to content

Lint against shadowing the prelude #8439

@kpreid

Description

@kpreid

What it does

Lints cases where a use, item declaration, or local binding shadows an item in the Rust prelude.

In the case of a use, it suggests instead using the containing module, i.e. replacing use std::io::Result; with use std::io;

Lint Name

shadow_prelude

Category

style, pedantic, restriction

Advantage

  • Code which redefines well-known names can be confusing to read, especially for beginners, or people who are trying to help a beginner but have only a code excerpt rather than a complete file with uses visible. (“This return type needs to be Result<(), MyError>.” “I did that, but it says that Result only takes 1 generic argument.” “Oh, you must have imported another Result; you need to remove that and change all your usages.”)

  • If an author intends to avoid shadowing, they may benefit from the lint catching when e.g. their IDE helpfully inserts an unwanted use.

  • It would also catch when a library author accidentally chooses a name for an item that conflicts with the standard prelude, allowing them to decide whether to reuse the name or choose a new one.

Drawbacks

  • It increases the verbosity of code obeying the restriction.

  • Shadowing Result and Error names is common enough practice that it might be objectionable to enable this lint by default, which limits its utility in the primary use case of helping beginners.

Example

use std::fs::read_to_string;
use std::io::Result;

fn load_config() -> Result<String> {
    read_to_string("config.toml")
}

Could be written as:

use std::fs::read_to_string;
use std::io;

fn load_config() -> io::Result<String> {
    read_to_string("config.toml")
}

Metadata

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