Implement Associated Type for Keys #3
37
src/bin/generic_trait_type_erasure.rs
Normal file
37
src/bin/generic_trait_type_erasure.rs
Normal file
@ -0,0 +1,37 @@
|
||||
|
||||
|
||||
pub trait Repository {
|
||||
type Key;
|
||||
|
||||
fn get_data(&self, key: Self::Key) -> String;
|
||||
fn set_data(&self, key: Self::Key, value: String);
|
||||
}
|
||||
|
||||
use std::any::Any;
|
||||
|
||||
trait Key: Any {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
fn from_str(s: &str) -> Self where Self: Sized;
|
||||
fn to_string(&self) -> String;
|
||||
}
|
||||
|
||||
impl<T: Any> Key for T {
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Key for String {
|
||||
fn from_str(s: &str) -> Self {
|
||||
s.to_string()
|
||||
}
|
||||
|
||||
fn to_string(&self) -> String {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait RepositoryTypeErased {
|
||||
fn get_data(&self, key: Key) -> String;
|
||||
fn set_data(&self, key: Key, value: String);
|
||||
}
|
Loading…
Reference in New Issue
Block a user