]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/explicit-self.rs
3d06a5562034cc0c383bcfba68ad93a498f66bc8
[rust.git] / src / test / run-pass / explicit-self.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 #![allow(unknown_features)]
12 #![feature(box_syntax)]
13
14 static tau: f64 = 2.0*3.14159265358979323;
15
16 struct Point {x: f64, y: f64}
17 struct Size {w: f64, h: f64}
18 enum shape {
19     circle(Point, f64),
20     rectangle(Point, Size)
21 }
22
23
24 fn compute_area(shape: &shape) -> f64 {
25     match *shape {
26         shape::circle(_, radius) => 0.5 * tau * radius * radius,
27         shape::rectangle(_, ref size) => size.w * size.h
28     }
29 }
30
31 impl shape {
32     // self is in the implicit self region
33     pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T)
34                          -> &'r T {
35         if compute_area(self) > threshold {a} else {b}
36     }
37 }
38
39 fn select_based_on_unit_circle<'r, T>(
40     threshold: f64, a: &'r T, b: &'r T) -> &'r T {
41
42     let shape = &shape::circle(Point{x: 0.0, y: 0.0}, 1.0);
43     shape.select(threshold, a, b)
44 }
45
46 #[derive(Clone)]
47 struct thing {
48     x: A
49 }
50
51 #[derive(Clone)]
52 struct A {
53     a: int
54 }
55
56 fn thing(x: A) -> thing {
57     thing {
58         x: x
59     }
60 }
61
62 impl thing {
63     pub fn bar(self: Box<thing>) -> int { self.x.a }
64     pub fn quux(&self) -> int { self.x.a }
65     pub fn baz<'a>(&'a self) -> &'a A { &self.x }
66     pub fn spam(self) -> int { self.x.a }
67 }
68
69 trait Nus { fn f(&self); }
70 impl Nus for thing { fn f(&self) {} }
71
72 pub fn main() {
73     let y: Box<_> = box thing(A {a: 10});
74     assert_eq!(y.clone().bar(), 10);
75     assert_eq!(y.quux(), 10);
76
77     let z = thing(A {a: 11});
78     assert_eq!(z.spam(), 11);
79 }