2018-08-30 12:18:55 +00:00
|
|
|
// run-pass
|
2014-12-22 17:04:23 +00:00
|
|
|
use std::ops::{Index, IndexMut};
|
|
|
|
|
2014-07-03 21:32:41 +00:00
|
|
|
struct Foo {
|
2015-03-26 00:06:52 +00:00
|
|
|
x: isize,
|
|
|
|
y: isize,
|
2014-07-03 21:32:41 +00:00
|
|
|
}
|
|
|
|
|
2015-03-26 00:06:52 +00:00
|
|
|
impl Index<isize> for Foo {
|
|
|
|
type Output = isize;
|
2015-01-03 15:40:36 +00:00
|
|
|
|
2015-03-26 00:06:52 +00:00
|
|
|
fn index(&self, z: isize) -> &isize {
|
2015-03-22 01:15:47 +00:00
|
|
|
if z == 0 {
|
2014-07-03 21:32:41 +00:00
|
|
|
&self.x
|
|
|
|
} else {
|
|
|
|
&self.y
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-26 00:06:52 +00:00
|
|
|
impl IndexMut<isize> for Foo {
|
|
|
|
fn index_mut(&mut self, z: isize) -> &mut isize {
|
2015-03-22 01:15:47 +00:00
|
|
|
if z == 0 {
|
2014-07-03 21:32:41 +00:00
|
|
|
&mut self.x
|
|
|
|
} else {
|
|
|
|
&mut self.y
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-10-31 09:44:10 +00:00
|
|
|
trait Int {
|
2015-03-26 00:06:52 +00:00
|
|
|
fn get(self) -> isize;
|
|
|
|
fn get_from_ref(&self) -> isize;
|
2014-10-31 09:44:10 +00:00
|
|
|
fn inc(&mut self);
|
|
|
|
}
|
|
|
|
|
2015-03-26 00:06:52 +00:00
|
|
|
impl Int for isize {
|
|
|
|
fn get(self) -> isize { self }
|
|
|
|
fn get_from_ref(&self) -> isize { *self }
|
2014-10-31 09:44:10 +00:00
|
|
|
fn inc(&mut self) { *self += 1; }
|
|
|
|
}
|
|
|
|
|
2014-07-03 21:32:41 +00:00
|
|
|
fn main() {
|
|
|
|
let mut f = Foo {
|
|
|
|
x: 1,
|
|
|
|
y: 2,
|
|
|
|
};
|
|
|
|
assert_eq!(f[1], 2);
|
|
|
|
f[0] = 3;
|
|
|
|
assert_eq!(f[0], 3);
|
|
|
|
{
|
|
|
|
let p = &mut f[1];
|
|
|
|
*p = 4;
|
|
|
|
}
|
|
|
|
{
|
|
|
|
let p = &f[1];
|
|
|
|
assert_eq!(*p, 4);
|
|
|
|
}
|
2014-10-31 09:44:10 +00:00
|
|
|
|
|
|
|
// Test calling methods with `&mut self`, `self, and `&self` receivers:
|
|
|
|
f[1].inc();
|
|
|
|
assert_eq!(f[1].get(), 5);
|
|
|
|
assert_eq!(f[1].get_from_ref(), 5);
|
2014-07-03 21:32:41 +00:00
|
|
|
}
|