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-01-03 15:40:36 +00:00
|
|
|
impl Index<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 {
|
|
|
|
if z == "x" {
|
2014-07-03 21:32:41 +00:00
|
|
|
&self.x
|
|
|
|
} else {
|
|
|
|
&self.y
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-03 15:40:36 +00:00
|
|
|
impl IndexMut<String> for Foo {
|
2015-03-22 01:16:57 +00:00
|
|
|
fn index_mut(&mut self, z: String) -> &mut isize {
|
|
|
|
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
|
|
|
|
2014-07-03 21:32:41 +00:00
|
|
|
println!("{}", f[s]);
|
2015-03-22 01:16:57 +00:00
|
|
|
//~^ ERROR cannot move out of `s` because it is borrowed
|
|
|
|
|
2014-07-03 21:32:41 +00:00
|
|
|
f[s] = 10;
|
2015-03-22 01:16:57 +00:00
|
|
|
//~^ ERROR cannot move out of `s` because it is borrowed
|
|
|
|
//~| ERROR use of moved value: `s`
|
|
|
|
|
2014-07-03 21:32:41 +00:00
|
|
|
let s = Bar {
|
|
|
|
x: 1,
|
|
|
|
};
|
2015-03-22 01:16:57 +00:00
|
|
|
let i = 2;
|
|
|
|
let _j = &i;
|
|
|
|
println!("{}", s[i]); // no error, i is copy
|
|
|
|
println!("{}", s[i]);
|
2018-11-05 12:55:00 +00:00
|
|
|
|
|
|
|
use_mut(rs);
|
2014-07-03 21:32:41 +00:00
|
|
|
}
|
2018-11-05 12:55:00 +00:00
|
|
|
|
|
|
|
fn use_mut<T>(_: &mut T) { }
|