]> git.lizzy.rs Git - rust.git/blob - src/test/ui/overloaded/overloaded-index.rs
Auto merge of #95454 - randomicon00:fix95444, r=wesleywiser
[rust.git] / src / test / ui / overloaded / overloaded-index.rs
1 // run-pass
2 use std::ops::{Index, IndexMut};
3
4 struct Foo {
5     x: isize,
6     y: isize,
7 }
8
9 impl Index<isize> for Foo {
10     type Output = isize;
11
12     fn index(&self, z: isize) -> &isize {
13         if z == 0 {
14             &self.x
15         } else {
16             &self.y
17         }
18     }
19 }
20
21 impl IndexMut<isize> for Foo {
22     fn index_mut(&mut self, z: isize) -> &mut isize {
23         if z == 0 {
24             &mut self.x
25         } else {
26             &mut self.y
27         }
28     }
29 }
30
31 trait Int {
32     fn get(self) -> isize;
33     fn get_from_ref(&self) -> isize;
34     fn inc(&mut self);
35 }
36
37 impl Int for isize {
38     fn get(self) -> isize { self }
39     fn get_from_ref(&self) -> isize { *self }
40     fn inc(&mut self) { *self += 1; }
41 }
42
43 fn main() {
44     let mut f = Foo {
45         x: 1,
46         y: 2,
47     };
48     assert_eq!(f[1], 2);
49     f[0] = 3;
50     assert_eq!(f[0], 3);
51     {
52         let p = &mut f[1];
53         *p = 4;
54     }
55     {
56         let p = &f[1];
57         assert_eq!(*p, 4);
58     }
59
60     // Test calling methods with `&mut self`, `self, and `&self` receivers:
61     f[1].inc();
62     assert_eq!(f[1].get(), 5);
63     assert_eq!(f[1].get_from_ref(), 5);
64 }