]> git.lizzy.rs Git - rust.git/blob - src/test/compile-fail/borrowck-overloaded-index.rs
make `IndexMut` a super trait over `Index`
[rust.git] / src / test / compile-fail / borrowck-overloaded-index.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 use std::ops::{Index, IndexMut};
12
13 struct Foo {
14     x: isize,
15     y: isize,
16 }
17
18 impl Index<String> for Foo {
19     type Output = isize;
20
21     fn index<'a>(&'a self, z: &String) -> &'a isize {
22         if *z == "x" {
23             &self.x
24         } else {
25             &self.y
26         }
27     }
28 }
29
30 impl IndexMut<String> for Foo {
31     fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize {
32         if *z == "x" {
33             &mut self.x
34         } else {
35             &mut self.y
36         }
37     }
38 }
39
40 struct Bar {
41     x: isize,
42 }
43
44 impl Index<isize> for Bar {
45     type Output = isize;
46
47     fn index<'a>(&'a self, z: &isize) -> &'a isize {
48         &self.x
49     }
50 }
51
52 fn main() {
53     let mut f = Foo {
54         x: 1,
55         y: 2,
56     };
57     let mut s = "hello".to_string();
58     let rs = &mut s;
59     println!("{}", f[s]);
60     //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable
61     f[s] = 10;
62     //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable
63     let s = Bar {
64         x: 1,
65     };
66     s[2] = 20;
67     //~^ ERROR cannot assign to immutable indexed content
68 }