Theory and Design of PL (CS 538)
April 01, 2020
trait Index<IdxType> {
type Output;
fn index(&self, idx: IdxType) -> &Self::Output;
}
trait IndexMut<IdxType> {
type Output;
fn index(&mut self, idx: IdxType) -> &mut Self::Output;
}
Output
is an associated type of the trait
*
operator to turn data into referencetrait Deref {
type Target; // returned ref will be to this type
fn deref(&self) -> &Self::Target;
}
trait DerefMut {
type Target; // returned ref will be to this type
fn deref(&mut self) -> &mut Self::Target;
}
trait Iterator {
// Type of item produced
type Item;
// Try to get the next item
fn next(&mut self) -> Option<Self::Item>;
}
next
returns next item, or nothing if no moreinto_iter()
: produced owned valuesiter()
: produce immutable referencesiter_mut()
: produce mutable referencesimpl Iterator for Point3DIter {
type Item = f32; // iterator produces floats (f32)
fn next(&mut self) -> Option<Self::Item> {
match self.cur_coord {
'x' => { self.cur_coord = 'y'; self.it_x.take() }
'y' => { self.cur_coord = 'z'; self.it_y.take() }
'z' => { self.cur_coord = 'a'; self.it_z.take() }
_ => None
}
}
}
move
syntax to make closure FnOnce