I'm trying to create a HashMap
containing a known value for a specific input. This input can accept multiple types, as long as they implement a certain trait. In this case, however, only a certain type is given, which Rust doesn't like.
Is there any way to "convert" a struct into a trait, or otherwise fix this issue?
#![allow(unused)]
use std::collections::HashMap;
use std::hash::*;
trait Element: Eq + PartialEq + Hash {}
trait Reaction<T: Element> {}
#[derive(Eq, Hash, PartialEq)]
struct Ion {
charge: u16
}
impl Element for Ion {}
#[derive(Eq, Hash, PartialEq)]
struct RedoxReaction<T: Element> { left: T }
impl<T: Element> Reaction<T> for RedoxReaction<T> {}
fn get_sep_database<T: Element>() -> HashMap<RedoxReaction<T>, f32> {
let mut map: HashMap<RedoxReaction<T>, f32> = HashMap::new();
let reaction = RedoxReaction {
left: Ion {
charge: 1
}
};
// note: expected type `RedoxReaction<T>`
// found type `RedoxReaction<Ion>`
map.insert(reaction, 0.000 as f32);
return map;
}
fn main() {
let db = get_sep_database();
let reaction = RedoxReaction {
left: Ion {
charge: 1
}
};
// expected this to be 0.000
let sep = db.get(&reaction);
}