Skip to content

Instantly share code, notes, and snippets.

@optozorax
Created September 14, 2019 16:54
Show Gist options
  • Save optozorax/f3d6e35f6bfe4470dc24839ff85b4343 to your computer and use it in GitHub Desktop.
Save optozorax/f3d6e35f6bfe4470dc24839ff85b4343 to your computer and use it in GitHub Desktop.
For with first and last element in Rust
trait Boundarized {
fn boundarize(self) -> Tripled<Self>;
}
struct Tripled<I> {
iter: I,
next: I,
}
impl<T> Boundarized for Iterator<Item = T> {
fn triple_split(self) -> Tripled<T> {
return Tripled { iter: self, next: None };
}
}
impl<I> Iterator for Tripled<I> where I: Iterator {
type Item = (usize, <I as Iterator>::Item);
fn next(&mut self) -> Option<(ForPosition, <I as Iterator>::Item)> {
}
}
enum ForPosition {
First,
Middle, // Такой элемент, который не является ни первым, ни последним
Last,
FirstLast, // Массив состоит из одного элемента, который является одновременно первым и последним
}
fn main() {
let mas = vec![1, 2, 3, 4, 5];
for (pos, &i) in &mas.boundarize() {
match pos {
ForPosition::First => {
println!("The first element is {}", i);
},
ForPosition::Middle => {
println!("The middle element is {}", i);
},
ForPosition::Last => {
println!("The last element is {}", i);
},
ForPosition::FirstLast => {
println!("The first and last element is {}", i);
},
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment