D. Ataro
D. Ataro

Reputation: 1821

Returning from inside for loop causes type mismatch

I am attempting to return a function pointer, which is located inside a for loop, from a function located in an impl of a struct.

fn locate_func(&self, string: &str) -> fn() -> bool {
    let mut func;

    for alt in &self.alts {
        return alt.func;
    }
}

There will be an if statement inside the for loop in the future, but as I am testing things at the very moment, it looks rather generic, and somewhat illogical.

The above code in my mind, is supposed to return the pointer to alt.func(), which clearly is a pointer, as it tells me so should I remove the return and semicolon of that line.

error[E0308]: mismatched types
  --> src\main.rs:42:3
   |
42 |            for alt in &self.alts
   |            ^ expected fn pointer, found ()
   |
   = note: expected type `fn() -> bool`
   = note:    found type `()`

Above is the error that is caused upon running locate_func(). I am clearly missing something as the aforementioned code is not working properly. Any hints?

Upvotes: 6

Views: 1471

Answers (1)

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88516

Your for-loop is the last expression inside the function. The compiler expects the last expression to evaluate to the return type. But all loops evaluate to () (unit or void), so the compiler has a classic type mismatch there.

The correct question to ask yourself is: what would happen if the return inside of the loop wouldn't be executed (for example, because the loop isn't executed at all, because self.alts is empty)? This would lead to problems, wouldn't it?

So you have to return a valid object after the for-loop to cover that case. But if you are certain that the spot after the loop will never be reached you can use unreachable!(); to tell the compiler what you already know. However, if the program will reach this spot, it will panic! So better make sure, you know for certain how the program behaves.

Upvotes: 10

Related Questions