Rust: Can't use HashMap<T, V> with T being an enum.

Created on 24 Feb 2015  路  2Comments  路  Source: rust-lang/rust

http://is.gd/PvCLA6

use std::collections::HashMap;

#[derive(Debug)]
enum Y {
    Y1,
    Y2,
}

#[derive(Debug)]
struct X {
    items : HashMap<Y, i8>,
}

Most helpful comment

HashMap has bounds on its first parameter (look at the "Methods" section): K: Eq + Hash. The slightly confusing error message is because the derived Debug implementation for X is trying to use the Debug implementation for HashMap, which has these bounds:

impl<K, V, S> Debug for HashMap<K, V, S> where K: Eq + Hash + Debug, V: Debug, S: HashState

But Y doesn't satisfy the bounds, so HashMap<Y, i8> doesn't implement Debug.

That is, your enum needs to implement those two traits, which can be done with derive:

use std::collections::HashMap;

#[derive(Debug, PartialEq, Eq, Hash)]
enum Y {
    Y1,
    Y2,
}

#[derive(Debug)]
struct X {
    items : HashMap<Y, i8>,
}

fn main()
{
    println!("Hello, world!")
}

Closing, but thanks for filing nonetheless!

All 2 comments

HashMap has bounds on its first parameter (look at the "Methods" section): K: Eq + Hash. The slightly confusing error message is because the derived Debug implementation for X is trying to use the Debug implementation for HashMap, which has these bounds:

impl<K, V, S> Debug for HashMap<K, V, S> where K: Eq + Hash + Debug, V: Debug, S: HashState

But Y doesn't satisfy the bounds, so HashMap<Y, i8> doesn't implement Debug.

That is, your enum needs to implement those two traits, which can be done with derive:

use std::collections::HashMap;

#[derive(Debug, PartialEq, Eq, Hash)]
enum Y {
    Y1,
    Y2,
}

#[derive(Debug)]
struct X {
    items : HashMap<Y, i8>,
}

fn main()
{
    println!("Hello, world!")
}

Closing, but thanks for filing nonetheless!

Can we maybe include this as a question & answer on Stack Overflow. It'll be helpful for beginners who learn through Googling their problems.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

withoutboats picture withoutboats  路  202Comments

withoutboats picture withoutboats  路  308Comments

GuillaumeGomez picture GuillaumeGomez  路  300Comments

nikomatsakis picture nikomatsakis  路  274Comments

Leo1003 picture Leo1003  路  898Comments