Created
August 24, 2013 23:37
-
-
Save lkuper/6331033 to your computer and use it in GitHub Desktop.
This file contains 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
// 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The error I'm getting is
The first error must be a consequence of the second, because if I just change all occurrences of
equals
tomy_equals
it compiles and runs fine.