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