Last active
February 25, 2022 16:30
-
-
Save stellasia/a0ed4331999d8bb2d53903564b0fcfa6 to your computer and use it in GitHub Desktop.
Medium_From_Python_To_Rust_Trait_Cache_2
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
| use std::collections::HashMap; | |
| trait CachableKey { | |
| fn get_key(&self) -> String; | |
| } | |
| trait CachableDataStr: CachableKey { | |
| /// Serialize to string | |
| /// Requires the trait CachableKey to be implemented on the struct | |
| fn serialize(&self) -> String; | |
| } | |
| trait CachableDataMap: CachableKey { | |
| /// Serialize to HashMap | |
| /// Requires the trait CachableKey to be implemented on the struct | |
| fn serialize(&self) -> HashMap<String, String>; | |
| } | |
| struct Item { | |
| name: String, | |
| value: String, | |
| } | |
| // if you forget this implementation, compiler will complain | |
| // that CachableDataStr can't be implemented for Item, since | |
| // CachableKey is a requirement | |
| impl CachableKey for Item { | |
| fn get_key(&self) -> String { | |
| self.name.clone() | |
| } | |
| } | |
| impl CachableDataStr for Item { | |
| fn serialize(&self) -> String { | |
| self.value.clone() | |
| } | |
| } | |
| impl CachableDataMap for Item { | |
| fn serialize(&self) -> HashMap<String, String> { | |
| // create mutable HashMap | |
| let mut m = HashMap::<String, String>::new(); | |
| // insert values | |
| m.insert(String::from("value"), self.value.clone()); | |
| // insert key: we can use the .get_key() method on self because | |
| // we have enforced the fact that structures implementing the CachableDataMap trait | |
| // MUST also implement CachableKey triat | |
| m.insert(String::from("key"), self.get_key()); | |
| // return created HashMap | |
| m | |
| } | |
| } | |
| fn main() { | |
| let item = Item {name: String::from("item1"), value: String::from("some_value") }; | |
| let serialized_data_str = CachableDataStr::serialize(&item); | |
| let serialized_data_map = CachableDataMap::serialize(&item); | |
| 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