1 use std::ops::{Index, IndexMut};
2 
3 struct Foo {
4     x: isize,
5     y: isize,
6 }
7 
8 impl Index<String> for Foo {
9     type Output = isize;
10 
index(&self, z: String) -> &isize11     fn index(&self, z: String) -> &isize {
12         if z == "x" {
13             &self.x
14         } else {
15             &self.y
16         }
17     }
18 }
19 
20 impl IndexMut<String> for Foo {
index_mut(&mut self, z: String) -> &mut isize21     fn index_mut(&mut self, z: String) -> &mut isize {
22         if z == "x" {
23             &mut self.x
24         } else {
25             &mut self.y
26         }
27     }
28 }
29 
30 struct Bar {
31     x: isize,
32 }
33 
34 impl Index<isize> for Bar {
35     type Output = isize;
36 
index<'a>(&'a self, z: isize) -> &'a isize37     fn index<'a>(&'a self, z: isize) -> &'a isize {
38         &self.x
39     }
40 }
41 
main()42 fn main() {
43     let mut f = Foo {
44         x: 1,
45         y: 2,
46     };
47     let mut s = "hello".to_string();
48     let rs = &mut s;
49 
50     println!("{}", f[s]);
51     //~^ ERROR cannot move out of `s` because it is borrowed
52 
53     f[s] = 10;
54     //~^ ERROR cannot move out of `s` because it is borrowed
55     //~| ERROR use of moved value: `s`
56 
57     let s = Bar {
58         x: 1,
59     };
60     let i = 2;
61     let _j = &i;
62     println!("{}", s[i]); // no error, i is copy
63     println!("{}", s[i]);
64 
65     use_mut(rs);
66 }
67 
use_mut<T>(_: &mut T)68 fn use_mut<T>(_: &mut T) { }
69