]>
Commit | Line | Data |
---|---|---|
b7449926 XL |
1 | // run-pass |
2 | #![allow(stable_features)] | |
1a4d82fc | 3 | |
b7449926 | 4 | // Test overloaded indexing combined with autoderef. |
c34b1796 | 5 | |
c34b1796 | 6 | #![feature(box_syntax, core)] |
1a4d82fc JJ |
7 | |
8 | use std::ops::{Index, IndexMut}; | |
9 | ||
10 | struct Foo { | |
c34b1796 AL |
11 | x: isize, |
12 | y: isize, | |
1a4d82fc JJ |
13 | } |
14 | ||
c34b1796 AL |
15 | impl Index<isize> for Foo { |
16 | type Output = isize; | |
1a4d82fc | 17 | |
c34b1796 AL |
18 | fn index(&self, z: isize) -> &isize { |
19 | if z == 0 { | |
1a4d82fc JJ |
20 | &self.x |
21 | } else { | |
22 | &self.y | |
23 | } | |
24 | } | |
25 | } | |
26 | ||
c34b1796 AL |
27 | impl IndexMut<isize> for Foo { |
28 | fn index_mut(&mut self, z: isize) -> &mut isize { | |
29 | if z == 0 { | |
1a4d82fc JJ |
30 | &mut self.x |
31 | } else { | |
32 | &mut self.y | |
33 | } | |
34 | } | |
35 | } | |
36 | ||
37 | trait Int { | |
c34b1796 AL |
38 | fn get(self) -> isize; |
39 | fn get_from_ref(&self) -> isize; | |
1a4d82fc JJ |
40 | fn inc(&mut self); |
41 | } | |
42 | ||
c34b1796 AL |
43 | impl Int for isize { |
44 | fn get(self) -> isize { self } | |
45 | fn get_from_ref(&self) -> isize { *self } | |
1a4d82fc JJ |
46 | fn inc(&mut self) { *self += 1; } |
47 | } | |
48 | ||
49 | fn main() { | |
c34b1796 | 50 | let mut f: Box<_> = box Foo { |
1a4d82fc JJ |
51 | x: 1, |
52 | y: 2, | |
53 | }; | |
54 | ||
55 | assert_eq!(f[1], 2); | |
56 | ||
57 | f[0] = 3; | |
58 | ||
59 | assert_eq!(f[0], 3); | |
60 | ||
61 | // Test explicit IndexMut where `f` must be autoderef: | |
62 | { | |
63 | let p = &mut f[1]; | |
64 | *p = 4; | |
65 | } | |
66 | ||
67 | // Test explicit Index where `f` must be autoderef: | |
68 | { | |
69 | let p = &f[1]; | |
70 | assert_eq!(*p, 4); | |
71 | } | |
72 | ||
73 | // Test calling methods with `&mut self`, `self, and `&self` receivers: | |
74 | f[1].inc(); | |
75 | assert_eq!(f[1].get(), 5); | |
76 | assert_eq!(f[1].get_from_ref(), 5); | |
77 | } |