Skip to content

Instantly share code, notes, and snippets.

@lkuper
Created August 24, 2013 23:37
Show Gist options
  • Save lkuper/6331033 to your computer and use it in GitHub Desktop.
Save lkuper/6331033 to your computer and use it in GitHub Desktop.
// Putting #[no_implicit_prelude] on this mod, because we want to
// define and use our own `equals`.
#[no_implicit_prelude]
pub mod default_methods_example {
// Explicitly import this stuff.
use std::clone::Clone;
use std::io::println;
trait Eq {
fn equals(&self, other: &Self) -> bool;
fn my_neq(&self, other: &Self) -> bool {
!self.equals(other)
}
}
#[deriving(Clone)]
enum Color { cyan, magenta, yellow, black }
impl Eq for Color {
fn equals(&self, other: &Color) -> bool {
match (*self, *other) {
(cyan, cyan) => { true }
(magenta, magenta) => { true }
(yellow, yellow) => { true }
(black, black) => { true }
_ => { false }
}
}
}
#[deriving(Clone)]
enum ColorTree {
leaf(Color),
branch(@ColorTree, @ColorTree)
}
impl Eq for ColorTree {
fn equals(&self, other: &ColorTree) -> bool {
match (*self, *other) {
(leaf(x), leaf(y)) => { x.equals(&y) }
(branch(l1, r1), branch(l2, r2)) => {
l1.equals(&*l2) && r1.equals(&*r2)
}
_ => { false }
}
}
}
// A bounded polymorphism example -- this is where traits are handy.
fn member<T: Eq + Clone>(elem: &T, vec: ~[T]) -> bool {
let mut i = 0;
while i <= vec.len() {
// Make local copies.
let elem = elem.clone();
let vec_elem = vec[i].clone();
if elem.equals(&vec_elem) { return true; }
i = i + 1;
}
return false;
}
pub fn test() {
assert!( cyan.equals(&cyan) );
assert!( magenta.equals(&magenta) );
assert!( !cyan.equals(&yellow) );
assert!( !magenta.equals(&cyan) );
println("Assertions all succeeded!");
}
}
pub fn main() {
use default_methods_example;
default_methods_example::test();
}
@lkuper
Copy link
Author

lkuper commented Aug 24, 2013

The error I'm getting is

$ ~/repos/rust/x86_64-apple-darwin/stage2/bin/rustc rust-traits-example.rs
rust-traits-example.rs:46:22: 46:26 error: $<2>$<2>mismatched types: expected `&@default_methods_example::ColorTree` but found `&default_methods_example::ColorTree` (expected @-ptr but found enum default_methods_example::ColorTree)
$<2>rust-traits-example.rs:46             l1.equals(&*l2) && r1.equals(&*r2)
                                                ^~~~
$<2>rust-traits-example.rs:46:12: 46:30 error: $<2>$<2>failed to find an implementation of trait std::cmp::TotalEq for default_methods_example::ColorTree
$<2>rust-traits-example.rs:46             l1.equals(&*l2) && r1.equals(&*r2)
                                      ^~~~~~~~~~~~~~~~~~

The first error must be a consequence of the second, because if I just change all occurrences of equals to my_equals it compiles and runs fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment