Skip to content

Instantly share code, notes, and snippets.

@Sgeo
Created August 14, 2016 08:23
Show Gist options
  • Save Sgeo/e16dd31cc8e39ae3ae85b465435c4ddf to your computer and use it in GitHub Desktop.
Save Sgeo/e16dd31cc8e39ae3ae85b465435c4ddf to your computer and use it in GitHub Desktop.
Specialization-based approach to an AnyMap-like structure
#![feature(specialization)]
#![allow(dead_code)]
struct Nil;
struct Cons<H, T>(H, T);
trait MayContain<T> {
fn get(&self) -> Option<&T>;
fn get_mut(&mut self) -> Option<&mut T>;
}
impl<T> MayContain<T> for Nil {
fn get(&self) -> Option<&T> {
None
}
fn get_mut(&mut self) -> Option<&mut T> {
None
}
}
impl<T, Tail: MayContain<T>> MayContain<T> for Cons<T, Tail> {
fn get(&self) -> Option<&T> {
Some(&self.0)
}
fn get_mut(&mut self) -> Option<&mut T> {
Some(&mut self.0)
}
}
impl<T, Head, Tail: MayContain<T>> MayContain<T> for Cons<Head, Tail> {
default fn get(&self) -> Option<&T> {
self.1.get()
}
default fn get_mut(&mut self) -> Option<&mut T> {
self.1.get_mut()
}
}
fn main() {
fn show_i32<T: MayContain<i32>>(t: &T) {
println!("{:?}", t.get());
}
let list1 = Cons(1i32, Cons(2i64, Cons("", Nil)));
let list2 = Cons(1i64, Cons(2i32, Cons("", Nil)));
let list3 = Cons(1i64, Cons("", Cons(3i32, Nil)));
let list4 = Cons(4i32, Cons("", Cons(3i32, Nil)));
let list5 = Cons(0i64, Cons("", Cons(1i64, Nil)));
show_i32(&list1);
show_i32(&list2);
show_i32(&list3);
show_i32(&list4);
show_i32(&list5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment