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