]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/overloaded-index.rs
0afdb24a81cc0dbf64dd86b437faeb4af54fa4bd
[rust.git] / src / test / run-pass / overloaded-index.rs
1 // Copyright 2014 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 use std::ops::{Index, IndexMut};
12
13 struct Foo {
14     x: int,
15     y: int,
16 }
17
18 impl Index<int> for Foo {
19     type Output = int;
20
21     fn index(&self, z: &int) -> &int {
22         if *z == 0 {
23             &self.x
24         } else {
25             &self.y
26         }
27     }
28 }
29
30 impl IndexMut<int> for Foo {
31     type Output = int;
32
33     fn index_mut(&mut self, z: &int) -> &mut int {
34         if *z == 0 {
35             &mut self.x
36         } else {
37             &mut self.y
38         }
39     }
40 }
41
42 trait Int {
43     fn get(self) -> int;
44     fn get_from_ref(&self) -> int;
45     fn inc(&mut self);
46 }
47
48 impl Int for int {
49     fn get(self) -> int { self }
50     fn get_from_ref(&self) -> int { *self }
51     fn inc(&mut self) { *self += 1; }
52 }
53
54 fn main() {
55     let mut f = Foo {
56         x: 1,
57         y: 2,
58     };
59     assert_eq!(f[1], 2);
60     f[0] = 3;
61     assert_eq!(f[0], 3);
62     {
63         let p = &mut f[1];
64         *p = 4;
65     }
66     {
67         let p = &f[1];
68         assert_eq!(*p, 4);
69     }
70
71     // Test calling methods with `&mut self`, `self, and `&self` receivers:
72     f[1].inc();
73     assert_eq!(f[1].get(), 5);
74     assert_eq!(f[1].get_from_ref(), 5);
75 }