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:

class="lang-rust prettyprint-override">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

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -