Skip to content

Instantly share code, notes, and snippets.

Created October 27, 2015 02:36
Show Gist options
  • Save anonymous/e3a8fe834bb383504bb4 to your computer and use it in GitHub Desktop.
Save anonymous/e3a8fe834bb383504bb4 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::ops;
/// An "iterable" is something that can be
/// iterated over in lifetime 'a.
pub trait Iterable<'a> {
type Item;
type Iter: Iterator<Item=&'a Self::Item>;
fn iter(&'a self) -> Self::Iter;
}
/// slices are iterable in any lifetime
impl<'a, T> Iterable<'a> for [T] {
type Item = T;
type Iter = std::slice::Iter<'a, T>;
fn iter(&'a self) -> Self::Iter {
return (&self).into_iter();
}
}
/// This is the same as Iterable, but
/// can be iterated with an exact size
trait ExactSizeIterable<'a> : Iterable<'a> where Self::Iter : ExactSizeIterator {}
impl<'a, T> ExactSizeIterable<'a> for [T] {}
fn print_em_and_change_em<T: ?Sized>(t: &mut T) where
T: for<'a> ExactSizeIterable<'a, Item=u32>,
T: ops::IndexMut<usize, Output=u32>{
println!("There are {} items!", t.iter().len());
for x in t.iter() {
println!("{}", x);
}
t[0] = 7u32;
}
fn main() {
let mut ts = vec!(1u32, 2u32, 3u32);
print_em_and_change_em(&mut ts[..]);
print_em_and_change_em(&mut ts[..]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment