Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created August 29, 2018 23:51
Show Gist options
  • Save rust-play/95f7a97993e7cbba83e669fa22eabf9f to your computer and use it in GitHub Desktop.
Save rust-play/95f7a97993e7cbba83e669fa22eabf9f to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::ops::Index;
struct Example<T: 'static>(&'static [T]);
impl<F, I, T> Index<F> for Example<T>
where
F: FnOnce(usize) -> I,
[T]: Index<I>
{
type Output = <[T] as Index<I>>::Output;
fn index(&self, f: F) -> &Self::Output {
&self.0[f(self.0.len())]
}
}
fn main() {
let my_slice = Example(&[1, 2, 3, 4]);
println!("Prefix: {:?}", &my_slice[|n| ..(n/2)]);
println!("Midpoint: {}", my_slice[|n| n/2]);
println!("Suffix: {:?}", &my_slice[|n| (n/2)..]);
println!("Suffix: {:?}", &my_slice[|n| n]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment