Skip to content

Instantly share code, notes, and snippets.

@superboum
Last active December 22, 2021 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superboum/f0a0d2c78098d538cd38ae13f794089f to your computer and use it in GitHub Desktop.
Save superboum/f0a0d2c78098d538cd38ae13f794089f to your computer and use it in GitHub Desktop.
A cheatsheet on how we can use Rust some features
use std::collections::*;
trait ListAcc{
// This is an associated type, a specific type of Generics
// You can also search for "Rust Associated Items" to know more about this concept
// Similarly to generics, we can set some bounds (ie. traits) on this type
// Here we chose our own Wave Trait and the std Clone trait
type E: Wave + Clone;
// Note the return type "Self::E", this is how we use an associated type
fn get(&self) -> &BTreeSet<Self::E>;
fn hello(&self) -> Option<String> {
Some(self.get().iter().next()?.do_wave())
}
}
// A simple trait
trait Wave {
fn do_wave(&self) -> String;
}
// This is the "newtype" pattern
// It is based on Rust's tuple structs
// Elements of a tuple struct can be accessed with self.0, self.1, etc.
// But it seems more idiomatic to use pattern matching.
// the "newtype" pattern is the only case where tuple struct are recommended.
// It is used to specialize native types to prevent mixing of data later
// But there is a drawbacks, we need to reimplement its traits
// Hopefully, we can derive some of them
#[derive(PartialEq,PartialOrd,Eq,Ord,Clone)]
struct Key(String);
// We also implement our own trait
impl Wave for Key {
fn do_wave(&self) -> String {
// First way to access our struct
// format!("HEY ! {}", &self.0)
// A more idiomatic way
match self { Key(internal_str) => format!("HEY ! {}", internal_str) }
}
}
struct KeyAcc {
acc: BTreeSet<Key>
}
// This how we implement a trait with an associated type
impl ListAcc for KeyAcc {
// We define our real type here
type E = Key;
fn get(&self) -> &BTreeSet<Self::E> {
return &self.acc
}
}
fn main() {
println!("hello world");
let mut kc = KeyAcc { acc: BTreeSet::<Key>::new() };
kc.acc.insert(Key("mamamia".to_string()));
println!("test: {:?}", kc.hello());
println!("the end");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment