Weird error in nested ifs

This code works well

    if input_count() == 2u8 {
        if input_owner(0).unwrap() == RECEIVER
            || input_owner(1).unwrap() == RECEIVER
        {
            // true
            return true;
        };
    };

however if i change the return true; to true, it gives me this error

35 |       if input_count() == 2u8 {
36 |           if input_owner(0).unwrap() == RECEIVER
   |  _________^
37 | |             || input_owner(1).unwrap() == RECEIVER
38 | |         {
39 | |             true
40 | |         };
   | |_________^ Mismatched types.
expected: ()
found:    bool.
help: The two branches of an if expression must return the same type.
41 |       };
   |
____

this code gives me the above error

    if input_count() == 2u8 {
        if input_owner(0).unwrap() == RECEIVER
            || input_owner(1).unwrap() == RECEIVER
        {
            true
        };
    };
1 Like

An expression (line without a ;) can be used to explicitly return a value from a function, but in the general case, it simply causes the code block in which it is immediately situated to be evaluated to that value.

So here, you’d simply be causing the whole if block to evaluate to true. This syntax would be used if you were assigning the result of the block to a variable (or using it to explicitly return from a function ) . However, for this to compile, you must handle the else case too.

For example:

// Will not compile. 
// Error : Mismatched types.
// The two branches of an if expression must return the same type.
let my_bool = if condition {
    true
};

Here, what does my_bool equal if the condition is false? Since you didn’t handle that case, the compiler assigns it the unit type () - which is not a boolean - and you get a mismatched type error. Handling the else case :

// code for illustation purposes. Is identical to `let my_bool = condition;`
let my_bool = if condition {
    true
}
else {
    false
};

Now, my_bool is definitely either true or false.

However, in the example given (for context, part of a predicate) what we want is to return early from the whole predicate if the condition is true. Whereas you might be able to force this into the implicit return syntax, the explicit return is probably cleaner here.

The rust book explains this quite concisely here.

3 Likes

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.