I'm coding a game with positions expressed as an Vec<u16>
. I'm caching best moves and losing positions for an exhaustive dfs. Best positions return a Guess
struct with a couple u16
members, while the losing positions include a single u16
reporting the depth at which it fails. I'm using a HashMap<Vec<u16>,Guess>
and a HashMap<Vec<u16>,u16>
to store and retrieve these. There are many overlapping functions including file saving and restoring, so I am trying to implement a generic Cache
struct to manage both types as follows:
trait Cacheable {}
impl Cacheable for u16 {}
impl Cacheable for Guess {}
pub struct Cache<T: Cacheable> {
hashmap: Vec<HashMap<Vec<u16>, T>>,
filename: String,
items_added: u32,
}
When loading the HashMap
from disk, I need to recover the hashmap value, but I can't find a way to create a function that returns type T
from the input Vec<u16>
. I've tried type-specific impl
like:
impl Cache<u16> {
fn make_value(data: &Vec<u16>) -> u16 {
data[0]
}
}
impl Cache<Guess> {
fn make_value(data: &Vec<u16>) -> Guess {
Guess::new_from_vec(data)
}
}
But the compiler complains about duplicate impl
for the same function, when I attempt value = Cache::make_value(&data);
. What is the idiomatic way to do this?