transform

Trait Transform

Source
pub trait Transform: Iterator {
    // Provided method
    fn transform<F, R>(self, predicate: F) -> TransformIter<Self, F, R> 
       where Self: Sized,
             F: FnMut(Self::Item) -> R,
             R: IntoIterator { ... }
}
Expand description

A trait that adds the transform()-function to all Iterators.

This function applies a closure that can transform an element in the existing iterator into zero or more elements in the resulting iterator.

Note that the closure is not called for the newly produces elements, only for those in the old iterator.

§Examples

use transform::Transform as _;

// Transform can be used for content-based expansion
let numbers = vec![1, 2, 3, 4, 5];
let numbers: Vec<i32> = numbers.into_iter().transform(|num| vec![num; num as usize]).collect();
assert_eq!(numbers, vec![1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]);

// We can also clone elements while doing so
let numbers = vec![1, 2, 3, 4, 5];
let numbers: Vec<i32> = numbers.iter().transform(|num| vec![*num; *num as usize]).collect();
assert_eq!(numbers, vec![1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]);

// Or change data types altogether
let chars = vec!['a', 'b', 'c'];
let padded_chars: Vec<u8> = chars.into_iter().transform(|c| [0, 0, 0, c as u8]).collect();
assert_eq!(padded_chars, vec![0, 0, 0, 97, 0, 0, 0, 98, 0, 0, 0, 99]);

Provided Methods§

Source

fn transform<F, R>(self, predicate: F) -> TransformIter<Self, F, R>
where Self: Sized, F: FnMut(Self::Item) -> R, R: IntoIterator,

Transforms each element in the iterator into zero or more elements of a (potentially) different type.

§Arguments
  • predicate: A closure that transforms each element in the iterator into an iterator that produces the zero-or-more elements of another type.
§Returns

A new TransformIter that can do as advertised.

Implementors§