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