Skip to content

Type/lifetime inference regression? #15298

Closed
@ebfe

Description

@ebfe

The following used to work:

use std::collections::hashmap::HashMap;

fn mkmap() -> HashMap<&str, int> {
    let mut map = HashMap::new();
    map.insert("foo", 1);
    map
}

pub fn main() {
    println!("{}", mkmap());
}

but fails to compile with current master due to

/home/mg/t.rs:6:5: 6:8 error: cannot infer an appropriate lifetime due to conflicting requirements
/home/mg/t.rs:6     map
                    ^~~
/home/mg/t.rs:5:5: 5:8 note: first, the lifetime cannot outlive the expression at 5:4...
/home/mg/t.rs:5     map.insert("foo", 1);
                    ^~~
/home/mg/t.rs:5:5: 5:8 note: ...so that automatically reference is valid at the time of borrow
/home/mg/t.rs:5     map.insert("foo", 1);
                    ^~~
/home/mg/t.rs:3:34: 7:2 note: but, the lifetime must be valid for the anonymous lifetime #1 defined on the block at 3:33...
/home/mg/t.rs:3 fn mkmap() -> HashMap<&str, int> {
/home/mg/t.rs:4     let mut map = HashMap::new();
/home/mg/t.rs:5     map.insert("foo", 1);
/home/mg/t.rs:6     map
/home/mg/t.rs:7 }
/home/mg/t.rs:6:5: 6:8 note: ...so that types are compatible (expected `std::collections::hashmap::HashMap<&str,int>` but found `std::collections::hashmap::HashMap<&str,int>`)
/home/mg/t.rs:6     map
                    ^~~
error: aborting due to previous error

The error can be avoided by adding type parameters to the HashMap::new() call.

use std::collections::hashmap::HashMap;

fn mkmap() -> HashMap<&str, int> {
    let mut map = HashMap::<&str, int>::new();
    map.insert("foo", 1);
    map
}

pub fn main() {
    println!("{}", mkmap());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions