rust - Is there a way to implement a custom enumerate method? -
rust - Is there a way to implement a custom enumerate method? -
i creating simple matrix implementation in rust. need next result:
class="lang-rs prettyprint-override">for (i, j, elem) in matrix.iter().enumerate() { ... }
but can see, enumerate()
method in iterator
trait pre-defined, , cannot override custom implementation, able homecoming (usize, usize, &t)
. there way implement custom enumerate()
method?
using rustc 1.0.0-dev (built 2015-04-06)
rust-nightly
.
it right cannot specialize implementation of iterator::enumerate
. however, can create enumerate
method straight on matrix
want:
struct matrix { value: u8, size: usize, } impl matrix { fn enumerate(&self) -> matrixenumerate { matrixenumerate { matrix: self, pos: 0 } } } struct matrixenumerate<'a> { matrix: &'a matrix, pos: usize, } impl<'a> iterator matrixenumerate<'a> { type item = (usize, usize, &'a u8); fn next(&mut self) -> option<(usize, usize, &'a u8)> { if self.pos < self.matrix.size { allow v = some((self.pos, self.pos, &self.matrix.value)); self.pos += 1; v } else { none } } } fn main() { allow m = matrix { value: 42, size: 10 }; (x, y, v) in m.enumerate() { println!("{}, {}: {}", x, y, v); } }
here, i'm skipping complexity of matrix , advancing downwards diagonal. real implementation has deal row-major or column-major iteration , wrapping @ end of row/column.
rust traits
Comments
Post a Comment