1

I'm using Hyper on the server side:

    //"req" is hyper::server::Request
    match req.headers().iter().collect().filter(|x| x.name() == "field123").first() {
      Some(...) => ...........
    }

Error:

    error[E0619]: the type of this value must be known in this context
   --> src/main.rs:123:31
    |
123 |                         match req.headers().iter().collect().filter(|x| x.name() == "field123").first() {
    |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

What "value" exactly? Why does the error occur?

How to fix it?

Ivani
  • 19
  • 3
  • 1
    Why do you need `collect` in the first place? You're taking a collection, turning it into an iterator, then immediately turning it back into a collection, followed by trying to invoke an iterator method (which aren't on collections). – DK. Mar 07 '18 at 02:42

1 Answers1

1

The compiler cannot deduce what sort of collection you want.

https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect

Because collect() is so general, it can cause problems with type inference. As such, collect() is one of the few times you'll see the syntax affectionately known as the 'turbofish': ::<>. This helps the inference algorithm understand specifically which collection you're trying to collect into.

Consider:

let input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let output = input.iter().map(|&x| x).collect();
println!("{:?}", output);

3 | let output = input.iter().map(|&x| x).collect();
  |     ^^^^^^
  |     |
  |     cannot infer type for `_`
  |     consider giving `output` a type

vs:

let input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let output = input.iter().map(|&x| x).collect::<Vec<i32>>();
println!("{:?}", output);

[1, 2, 3, 4, 5, 6, 7, 8, 9]

You probably want something along these lines, although I'm not sure what, based on your tiny snippet:

let input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let output = input.iter().filter(|&x| *x > 5).nth(0);
println!("{:?}", output);

Otherwise, explicitly use collect::<...> to resolve the output type.

Doug
  • 32,844
  • 38
  • 166
  • 222