Closed
Description
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