Last active
February 25, 2022 16:29
-
-
Save stellasia/5d49e5b55339e5eb3262b10832b71dc0 to your computer and use it in GitHub Desktop.
Medium_From_Python_To_Rust_Trait_Cache
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
| class CacheMixin: | |
| def get_key(self): | |
| raise NotImplementedError() | |
| def serialize(self): | |
| raise NotImplementedError() | |
| class Item(CacheMixin): | |
| def __init__(self, name, value): | |
| self.name = name | |
| self.value = value | |
| def get_key(self): | |
| return self.name | |
| def serialize(self): | |
| return str(self.value) | |
| def main(): | |
| item = Item("item1", "some_value") | |
| print(item.get_key(), item.serialize()) | |
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
| trait Cachable { | |
| fn get_key(&self) -> String; | |
| fn serialize(&self) -> String; | |
| } | |
| struct Item { | |
| name: String, | |
| value: String, | |
| } | |
| impl Cachable for Item { | |
| fn get_key(&self) -> String { | |
| // 'return' keyword is optional here | |
| self.name.clone() | |
| } | |
| fn serialize(&self) -> String { | |
| self.value.clone() | |
| } | |
| } | |
| fn main() { | |
| let item = Item {name: String::from("item1"), value: String::from("some_value") }; | |
| println!("{}, {}", item.get_key(), item.serialize()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment