Last active
February 25, 2022 16:22
-
-
Save stellasia/57e3b23924beb62f0e18fd8e894810c6 to your computer and use it in GitHub Desktop.
Medium_From_Python_To_Rust_Trait_Cache_3
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
| // extension from https://gist.github.com/stellasia/a0ed4331999d8bb2d53903564b0fcfa6 | |
| use std::fmt::Debug; | |
| trait Cachable<T: Debug>: CachableKey { | |
| fn serialize_and_print(&self) { | |
| /// print serialized data for debugging | |
| /// this trait method has a default implementation, that can | |
| /// be overwritten in trait implementations if required | |
| let data = self.serialize(); | |
| println!("{}:?", data) | |
| } | |
| fn serialize(&self) -> T ; | |
| } | |
| impl Cachable<String> for Item { | |
| // we do not have to implement 'serialize_and_print' which has a default implementation | |
| fn serialize(&self) -> String { | |
| self.value.clone() | |
| } | |
| } | |
| fn main() { | |
| let item = Item {name: String::from("item1"), value: String::from("some_value") }; | |
| Cachable::<String>::serialize_and_print(&item); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment