Is there a builtin identity function in Rust?
Answering your question
After Rust 1.33, see the sibling answer.
Before Rust 1.33, there is no such function in stable Rust. You can create your own:
fn id<T>(v: T) -> T { v }
Although most people just inline the code, as you did.
Solving your problem
After Rust 1.29, use Iterator::flatten
:
let v = vec![Some(1), None, Some(2)];
for i in v.into_iter().flatten() {
println!("{}", i);
}
Before Rust 1.29, use Iterator::flat_map
:
let v = vec![Some(1), None, Some(2)];
for i in v.into_iter().flat_map(|o| o) {
println!("{}", i);
}
See also:
- Why does `Option` support `IntoIterator`?
There is an std::convert::identity
function as of Rust 1.33.0.