Hi, I'm learning Rust for 1 day and I would like to implement my own .each
iterator.
It should work similar to JavaScript version where you can call each
on an array and it will simply loop over the items.
// JavaScript version
let values = [1,2,3,4,5];
values.each((item) => {
console.log('Value: ', item);
});
I know in rust, you would normally do a for loop
let values = vec![1,2,3,4,5];
for item in values {
println!("Value: {}", item);
}
but for a learning purpose I want to implement it like this.
I was able to make it work for vector of integers, but I have a trouble to implement it with generics, so it can work with anything that's iterable.
fn main() {
let values = vec![1, 2, 3];
values.each(|item| println!("Value: {}", item));
}
pub trait Each {
fn each<F>(&self, f: F)
where
F: Fn(i32) -> ();
}
impl Each for Vec<i32> {
fn each<F>(&self, f: F)
where
F: Fn(i32) -> (),
{
for &value in self {
f(value);
}
}
}
Bonus would be if I could chain iterator calls on top of each to make something like this possible
fn main() {
let values = vec![1, 2, 3];
values
.iter()
.each(|item| println!("Before: {}", item))
.map(|item| item * 10)
.each(|item| println!("After {}", item))
.collect();
}
Thanks for help