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