Search code examples
rusthashmap

How do I initialise a HashMap with specific key and value types?


I read the docs on HashMap and I understand that they can have alternate custom types. This example is given in the docs:

type Accounts<'a> = HashMap<Account<'a>, AccountInfo<'a>>;
let mut accounts: Accounts = HashMap::new();

I would prefer to not define an explicit type. I have a function that expects a mutable HashMap<PathBuf, bool>:

pub fn parse(
    visited: &mut HashMap<PathBuf, bool>,
    path: PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    unimplemented!()
}

In my "main" function, I am calling "parse" like this:

let mut visited = HashMap::new();
parse(&mut visited, args.path)?;

The code compiles, but I would like to be more explicit and define the types when creating the visited variable. It looks like the following syntax is not correct:

let mut visited = HashMap<PathBuf, bool>::new();

Is there any way to do this?


Solution

  • Parameters to generics in an expression (as opposed to a type) need an extra ::. The correct syntax is:

    let mut visited = HashMap::<PathBuf, bool>::new();
    

    This construct is sometimes referred to as the "turbofish". I can't find a canonical reference about it (the word occurs only once in the Book), but this article is pretty good.