Skip to content

Instantly share code, notes, and snippets.

@stellasia
Last active February 25, 2022 16:29
Show Gist options
  • Select an option

  • Save stellasia/5d49e5b55339e5eb3262b10832b71dc0 to your computer and use it in GitHub Desktop.

Select an option

Save stellasia/5d49e5b55339e5eb3262b10832b71dc0 to your computer and use it in GitHub Desktop.
Medium_From_Python_To_Rust_Trait_Cache
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())
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