I've a frames: Vec<Vec<u16>>
, where the inner vector can have either 1 or 2 elements. I want to take 2 elements starting at index i
, for which the following possibilities exist:
-
frames[i]
has 2 elements and there's noframes[i+1]
. -
frames[i]
has 1 element andframes[i+1]
has 1 element. -
frames[i]
has 1 element andframes[i+1]
has 2 elements. -
frames[i]
has 2 elements andframes[i+1]
has 1 element. -
frames[i]
has 2 elements andframes[i+1]
has 2 elements.
I've come up with the following options:
Option 1:
frames[i]
.iter()
.chain(frames.get(i + 1).unwrap_or(&vec![]).iter())
.take(2)
Option 2:
frames
[i..cmp::min(i + 2, frames.len())]
.iter()
.flat_map(|f| f.iter())
.take(2)
It'd be nice if I could do frames[i..i + 2]
(or the get
call) without worrying about the length, but it throws out of bounds exception. Some other languages, like Python and Go, would return the remaining of the slice if the end index is out of bounds, but Rust doesn't. Is there a cleaner way to do this?