]> git.lizzy.rs Git - rust.git/blob - src/test/ui/overloaded/overloaded-index-autoderef.rs
Merge commit '2bb3996244cf1b89878da9e39841e9f6bf061602' into sync_cg_clif-2022-12-14
[rust.git] / src / test / ui / overloaded / overloaded-index-autoderef.rs
1 // run-pass
2 #![allow(stable_features)]
3
4 // Test overloaded indexing combined with autoderef.
5
6 use std::ops::{Index, IndexMut};
7
8 struct Foo {
9     x: isize,
10     y: isize,
11 }
12
13 impl Index<isize> for Foo {
14     type Output = isize;
15
16     fn index(&self, z: isize) -> &isize {
17         if z == 0 {
18             &self.x
19         } else {
20             &self.y
21         }
22     }
23 }
24
25 impl IndexMut<isize> for Foo {
26     fn index_mut(&mut self, z: isize) -> &mut isize {
27         if z == 0 {
28             &mut self.x
29         } else {
30             &mut self.y
31         }
32     }
33 }
34
35 trait Int {
36     fn get(self) -> isize;
37     fn get_from_ref(&self) -> isize;
38     fn inc(&mut self);
39 }
40
41 impl Int for isize {
42     fn get(self) -> isize { self }
43     fn get_from_ref(&self) -> isize { *self }
44     fn inc(&mut self) { *self += 1; }
45 }
46
47 fn main() {
48     let mut f: Box<_> = Box::new(Foo {
49         x: 1,
50         y: 2,
51     });
52
53     assert_eq!(f[1], 2);
54
55     f[0] = 3;
56
57     assert_eq!(f[0], 3);
58
59     // Test explicit IndexMut where `f` must be autoderef:
60     {
61         let p = &mut f[1];
62         *p = 4;
63     }
64
65     // Test explicit Index where `f` must be autoderef:
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 }