Skip to content

Improve compile errors for type mismatch when encoutering unwrap_or #127545

Closed
@tesuji

Description

@tesuji

Given this code:

use std::collections::HashMap;

pub fn get(index: &HashMap<usize, Vec<i32>>, id: usize) -> &[i32] {
    index.get(&id).unwrap_or(&[])
}

Current error, for the motivating use case above:

error[E0308]: mismatched types
   --> src/lib.rs:5:30
    |
5   |     index.get(&id).unwrap_or(&[])
    |                    --------- ^^^ expected `&Vec<i32>`, found `&[_; 0]`
    |                    |
    |                    arguments to this method are incorrect
    |
    = note: expected reference `&Vec<i32>`
               found reference `&[_; 0]`
help: the return type of this call is `&[_; 0]` due to the type of the argument passed
   --> src/lib.rs:5:5
    |
5   |     index.get(&id).unwrap_or(&[])
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^---^
    |                              |
    |                              this argument influences the return type of `unwrap_or`

It should be possible for rustc to suggest replacing this specific instantiation of unwrap_or with map_or(&[], Vec::as_slice). Maybe similarly for some other common cases: map_or("", String::as_str).

Originally posted by @dtolnay in rust-lang/libs-team#407 (comment)

@rustbot label -T-rustdoc T-compiler

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.T-compilerRelevant to the compiler 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