Skip to content

split redundant_type_annotations into "redundant" and "unnecessary" flavors #14390

Open
@eric-seppanen

Description

@eric-seppanen

Description

I enabled redundant_type_annotations on a large codebase, and found that it flags some code that needs improvement, but also a lot of things that seem fine as-is.

I agree with the lint that type annotations like this are redundant:

let socket: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);

let start: SystemTime = SystemTime::now();

... because it literally spells out the type twice.

I also agree that this type annotation is unnecessary:

let mut success: bool = true;

... because true and false are keywords, and there is no chance of confusion what type they are.

But I don't think the same thinking stretches to all type annotations, just because a function returns an unambiguous type that could have been inferred. Some examples:

// We see `len()` and assume `usize`, but `Metadata::len()` is different.
let file_size: u64 = file.metadata()?.len();

// I want to clarify that this is `PathBuf` and not  `&Path` or `OsString`.
let mut runner_dir: PathBuf = std::env::temp_dir();

// I want to clarify that that `DirEntry::file_name()` returns `OsString` and not  `&Path` or `PathBuf`.
let entry_name: OsString = entry.file_name();

// I want to remember that this is `ThreadRng` and not `SmallRng` or `OsRng`.
let mut rng: ThreadRng = rand::rng();

In these cases I would defer to the programmer, who probably added the type annotation to help them while debugging or refactoring, or as a readability aid: it may be easier for humans to understand/review the code if some of the types are visible.

Perhaps these should be handled as separate lints:

  • redundant_type_annotations: only fires for "redundant" type annotations, where the type was already named in the rvalue.
  • unnecessary_type_annotations: all the other cases where type annotations could be elided.

I didn't see any debate on this topic when the lint was created (#10570).

Version

rustc 1.85.0 (4d91de4e4 2025-02-17)
binary: rustc
commit-hash: 4d91de4e48198da2e33413efdcd9cd2cc0c46688
commit-date: 2025-02-17
host: x86_64-unknown-linux-gnu
release: 1.85.0
LLVM version: 19.1.7

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsC-enhancementCategory: Enhancement of lints, like adding more cases or adding help messages

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions