Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a builtin identity function in Rust?

Tags:

rust

I have a vector of Options and I want to filter only the Somes. I use filter_map with identity:

let v = vec![Some(1), None, Some(2)];
for i in v.into_iter().filter_map(|o| o) {
    println!("{}", i);
}

Is there a builtin function permitting to write something like filter_map(identity)?

like image 304
Boiethios Avatar asked Aug 30 '17 20:08

Boiethios


People also ask

Which of the following is an identity function?

Hence f:R→R,f(x)=x is an identity function.

Is identity function continuous?

Properties of Identity FunctionIn topological space, this function is always continuous.

What is a identity function Python?

Overview. The identity() function from numpy library is used to return the identity matrix. Note: An identity matrix is the type of matrix in which all the elements on the main diagonal are ones (1) and all other elements are zeros (0).


1 Answers

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`?
like image 89
Shepmaster Avatar answered Oct 14 '22 07:10

Shepmaster