2014-12-22 09:04:23 -08:00
|
|
|
use std::ops::{Index, IndexMut};
|
|
|
|
|
2014-07-03 14:32:41 -07:00
|
|
|
struct Foo {
|
2015-01-08 21:54:35 +11:00
|
|
|
x: isize,
|
|
|
|
y: isize,
|
2014-07-03 14:32:41 -07:00
|
|
|
}
|
|
|
|
|
2015-03-21 21:16:57 -04:00
|
|
|
impl<'a> Index<&'a String> for Foo {
|
2015-01-08 21:54:35 +11:00
|
|
|
type Output = isize;
|
2015-01-03 10:40:36 -05:00
|
|
|
|
2015-03-21 21:16:57 -04:00
|
|
|
fn index(&self, z: &String) -> &isize {
|
2015-02-01 21:53:25 -05:00
|
|
|
if *z == "x" {
|
2014-07-03 14:32:41 -07:00
|
|
|
&self.x
|
|
|
|
} else {
|
|
|
|
&self.y
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-21 21:16:57 -04:00
|
|
|
impl<'a> IndexMut<&'a String> for Foo {
|
|
|
|
fn index_mut(&mut self, z: &String) -> &mut isize {
|
2015-02-01 21:53:25 -05:00
|
|
|
if *z == "x" {
|
2014-07-03 14:32:41 -07:00
|
|
|
&mut self.x
|
|
|
|
} else {
|
|
|
|
&mut self.y
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Bar {
|
2015-01-08 21:54:35 +11:00
|
|
|
x: isize,
|
2014-07-03 14:32:41 -07:00
|
|
|
}
|
|
|
|
|
2015-01-08 21:54:35 +11:00
|
|
|
impl Index<isize> for Bar {
|
|
|
|
type Output = isize;
|
2015-01-03 10:40:36 -05:00
|
|
|
|
2015-03-21 21:16:57 -04:00
|
|
|
fn index<'a>(&'a self, z: isize) -> &'a isize {
|
2014-07-03 14:32:41 -07:00
|
|
|
&self.x
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let mut f = Foo {
|
|
|
|
x: 1,
|
|
|
|
y: 2,
|
|
|
|
};
|
|
|
|
let mut s = "hello".to_string();
|
|
|
|
let rs = &mut s;
|
2015-03-21 21:16:57 -04:00
|
|
|
println!("{}", f[&s]);
|
2019-04-22 08:40:08 +01:00
|
|
|
//~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable
|
2015-03-21 21:16:57 -04:00
|
|
|
f[&s] = 10;
|
2019-04-22 08:40:08 +01:00
|
|
|
//~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable
|
2014-07-03 14:32:41 -07:00
|
|
|
let s = Bar {
|
|
|
|
x: 1,
|
|
|
|
};
|
|
|
|
s[2] = 20;
|
2019-07-07 14:16:58 +01:00
|
|
|
//~^ ERROR cannot assign to data in an index of `Bar`
|
2018-04-09 05:28:00 -04:00
|
|
|
drop(rs);
|
2014-07-03 14:32:41 -07:00
|
|
|
}
|