Last active
February 25, 2022 16:22
-
-
Save stellasia/610eb6df27450a29eb75746d2173bc06 to your computer and use it in GitHub Desktop.
Medium_From_Python_To_Rust_Cache_with_Generics_1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Item & CachableKey from https://gist.github.com/stellasia/a0ed4331999d8bb2d53903564b0fcfa6 | |
| trait Cachable<T>: CachableKey { | |
| /// T can be any type (String, HashMap or ...) | |
| /// It is used to tell Rust that it will be the return type of the 'serialize' method | |
| fn serialize(&self) -> T ; | |
| } | |
| // implement cache for T=String, ie the serialize method will return String | |
| impl Cachable<String> for Item { | |
| fn serialize(&self) -> String { | |
| self.value.clone() | |
| } | |
| } | |
| // implement cache for T=HashMap<String, String>, ie the serialize method will return HashMap | |
| impl Cachable<HashMap<String, String>> for Item { | |
| fn serialize(&self) -> HashMap<String, String> { | |
| let mut m = HashMap::<String, String>::new(); | |
| m.insert(String::from("value"), self.value.clone()); | |
| m.insert(String::from("key"), self.get_key()); | |
| m | |
| } | |
| } | |
| fn main() { | |
| let item = Item {name: String::from("item1"), value: String::from("some_value") }; | |
| // access the serialize method of Item that returns "String" | |
| let serialized_data_str: String = item.serialize(); | |
| // access the serialize method of Item that returns "HashMap" | |
| let serialized_data_map: HashMap<String, String> = item.serialize(); | |
| println!("{}, {}, {:?}", CachableKey::get_key(&item), serialized_data_str, serialized_data_map) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment