19

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)?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Boiethios
  • 38,438
  • 19
  • 134
  • 183

2 Answers2

18

There is an std::convert::identity function as of Rust 1.33.0.

ændrük
  • 782
  • 1
  • 8
  • 22
Boiethios
  • 38,438
  • 19
  • 134
  • 183
12

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I made another one when the item is not moved: `fn id_deref(v: &Option) -> Option<&T> {v.as_ref()}` – Boiethios Aug 31 '17 at 08:59
  • 3
    @Boiethios I'd be very hesitant to call that anything like "identity" considering it changes the value. I'd also not call it "deref" because that means something in Rust which isn't what that function does. Also, that function is redundant; you can just say `Option::as_ref` instead. – Shepmaster Aug 31 '17 at 12:54