Last active
December 6, 2018 15:07
-
-
Save MrQubo/9f95654fd285d3bc95cbe37a9ed44877 to your computer and use it in GitHub Desktop.
Multi-index operator attempt in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod Foo | |
{ | |
use ::std::ops; | |
pub struct Bar<T> | |
{ | |
a: T, | |
} | |
impl<T> Bar<T> | |
{ | |
pub fn new(a: T) -> Bar<T> | |
{ | |
Bar { a } | |
} | |
} | |
pub struct BarHelper<'a, T, I> | |
where Bar<T>: 'a | |
{ | |
idx: I, | |
bar: &'a Bar<T>, | |
} | |
impl<'a> ops::Index<i32> for &'a Bar<i32> | |
{ | |
type Output = BarHelper<'a, i32, i32>; | |
fn index(&self, idx: i32) -> Self::Output | |
{ | |
BarHelper { idx, bar: &self } | |
} | |
} | |
impl<'a> ops::Index<i32> for BarHelper<'a, i32, i32> | |
{ | |
type Output = i32; | |
fn index(&self, idx: i32) -> Self::Output | |
{ | |
self.bar.a * self.idx + idx | |
} | |
} | |
} /* mod Foo */ | |
use Foo::Bar; | |
fn main() | |
{ | |
let x = Bar::new(2 as i32); | |
assert_eq!(x[3][4], 2*3 + 4); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment