HiDefender
HiDefender

Reputation: 2378

Cannot infer value type even when explict

I need to split a string on whitespace and several other chars.

let mut text = String::from("foo,bar baz");
for word in text.split(|c| c.is_whitespace::<char>() || c == ',' ).filter(|&s| !s.is_empty()) {
    println!("{}", word);
}

However the compiler says:

error: the type of this value must be known in this context
 --> src/main.rs:4:32
  |
4 |     for word in text.split(|c| c.is_whitespace::<char>() || c == ',').filter(|&s| !s.is_empty()) {
  |                                ^^^^^^^^^^^^^^^^^^^^^^^^^

What am I doing wrong? Why can it not infer the type?

Upvotes: 2

Views: 112

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161627

The .split method accepts anything satisfying the Pattern<'a> trait bound. In this case, Rust cannot know what type of function this is because it does not know what the type of the function parameter is.

Looking at Pattern there is an implementation for FnMut:

impl<'a, F> Pattern<'a> for F 
where
    F: FnMut(char) -> bool,

To tell the compiler that this is the pattern you want, you need to give enough information for it to know that your closure matches this.

In this case, this means you can add : char. You must also remove ::<char>, because it is an unneeded type parameter. e.g.

text.split(|c| c.is_whitespace::<char>() || c == ',' )

to

text.split(|c: char| c.is_whitespace() || c == ',' )

Upvotes: 3

Related Questions