Hi --
I am trying to experiment with the type system with a real world example. Suppose I want to define a key-value store package. I start out by defining the behavior:
use std::{collections::HashMap, hash::Hash};
pub trait Store<T: Eq + Hash + Clone> {
fn new() -> Self;
fn get(&self, key: &T) -> Option<&T>;
fn set(&mut self, key: T, value: T) -> Option<T>;
}
My understand: I define an interface (or trait) with three methods over the type T
which can be any type as long as it implements the Eq
, Hash
, and Clone
traits.
With that done, I want to define a naive implementation of a key-value store that's just a wrapped HashMap
(same file):
pub struct NaiveStore<T: Eq + Hash> {
storage: std::collections::HashMap<T, T>
}
From that, I make it a Store<T>
(same file):
impl<T: Eq + Hash + Clone> Store<T> for NaiveStore<T> {
fn new() -> Self {
Self {
storage: std::collections::HashMap::new(),
}
}
fn get(&self, key: &T) -> Option<&T> {
return self.storage.get(&key)
}
fn set(&mut self, key: T, value: T) -> Option<T> {
self.storage.insert(key, value)
}
}
The compiler seems happy, I go in another directory and create an example that consumes this kv library:
use kvrust;
fn main() {
println!("Hello, world!");
let mut store = kvrust::NaiveStore::new();
let k = String::from_str("testKey").unwrap();
let v = String::from_str("testValue").unwrap();
store.set(k.clone(), v.clone());
println!("for key={} we have value={}", k, store.get(&k).unwrap());
}
But, I meet the following error:
error[E0599]: no function or associated item named `new` found for struct `NaiveStore` in the current scope
--> src/main.rs:7:41
|
7 | let mut store = kvrust::NaiveStore::new();
| ^^^ function or associated item not found in `NaiveStore<_>
I assumed this was related to the fact that when I create a NaiveStore
I do not specify the type and the new
function doesn't specify it. But I am being told that this is somehow inferred by the compiler. Moreover, the error message says it cannot find a matching method new
which tells me I might be mis-calling the method. Can I anyone point me to:
- how to fix the error?
- what's the idiomatic way to implement this pattern?
Thanks