]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/typeclasses-eq-example-static.rs
Add a doctest for the std::string::as_string method.
[rust.git] / src / test / run-pass / typeclasses-eq-example-static.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 // Example from lkuper's intern talk, August 2012 -- now with static
13 // methods!
14 use Color::{cyan, magenta, yellow, black};
15 use ColorTree::{leaf, branch};
16
17 trait Equal {
18     fn isEq(a: &Self, b: &Self) -> bool;
19 }
20
21 enum Color { cyan, magenta, yellow, black }
22
23 impl Equal for Color {
24     fn isEq(a: &Color, b: &Color) -> bool {
25         match (*a, *b) {
26           (cyan, cyan)       => { true  }
27           (magenta, magenta) => { true  }
28           (yellow, yellow)   => { true  }
29           (black, black)     => { true  }
30           _                  => { false }
31         }
32     }
33 }
34
35 enum ColorTree {
36     leaf(Color),
37     branch(Box<ColorTree>, Box<ColorTree>)
38 }
39
40 impl Equal for ColorTree {
41     fn isEq(a: &ColorTree, b: &ColorTree) -> bool {
42         match (a, b) {
43           (&leaf(x), &leaf(y)) => { Equal::isEq(&x, &y) }
44           (&branch(ref l1, ref r1), &branch(ref l2, ref r2)) => {
45             Equal::isEq(&**l1, &**l2) && Equal::isEq(&**r1, &**r2)
46           }
47           _ => { false }
48         }
49     }
50 }
51
52 pub fn main() {
53     assert!(Equal::isEq(&cyan, &cyan));
54     assert!(Equal::isEq(&magenta, &magenta));
55     assert!(!Equal::isEq(&cyan, &yellow));
56     assert!(!Equal::isEq(&magenta, &cyan));
57
58     assert!(Equal::isEq(&leaf(cyan), &leaf(cyan)));
59     assert!(!Equal::isEq(&leaf(cyan), &leaf(yellow)));
60
61     assert!(Equal::isEq(&branch(box leaf(magenta), box leaf(cyan)),
62                 &branch(box leaf(magenta), box leaf(cyan))));
63
64     assert!(!Equal::isEq(&branch(box leaf(magenta), box leaf(cyan)),
65                  &branch(box leaf(magenta), box leaf(magenta))));
66
67     println!("Assertions all succeeded!");
68 }