Cannot infer type for `B` for filter_map().sum()

后端 未结 2 768
醉梦人生
醉梦人生 2020-12-21 08:02

The code below reads numbers, sums them, then prints the sum. I\'ve tried few annotations, but it didn\'t work. I must be missing something. How could I make it work?

<
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 08:54

    Let's look up the signature of filter_map to see, what the complain is about:

    fn filter_map(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option, 
    

    Okay, so Option is the result, which means he cannot infer what w.parse().ok() will be.

    Let's try to give him a hint

    .filter_map(|w| w.parse::().ok())
    

    Let's compile an see.... Hurray!

    So, lesson learned: Look up the signature and try to figure out, which part the compiler cannot infer and try to specify it.

提交回复
热议问题