If else with * is interpreted as deref not mult

I run into the following problem.

fn main() {
    let t = if false {
        1
    } else {
        if true {
            2
        } else {
            3
        }
        *4
    } ;
}

here * is interpreted as a deref not as multiplication.
what is the rule?
because this works

fn main() {
    let t = if false {
        1
    } else {
        if true {
            2
        } else {
            3
        }
    } ;
}

and this

fn main() {
    let t = if false {
        1
    } else {
        (if true {
            2
        } else {
            3
        })
        *4
    } ;
}

From the reference:

An expression that consists of only a block expression or control flow expression, if used in a context where a statement is permitted, can omit the trailing semicolon. This can cause an ambiguity between it being parsed as a standalone statement and as a part of another expression; in this case, it is parsed as a statement.

4 Likes

Note that for simple cases you can avoid the parentheses by reorganizing the code to make sure the compiler sees an expression:

fn main() {
    let t = if false {
        1
    } else {
        4 * if true {
            2
        } else {
            3
        }
    };
}
1 Like

I only intuitively understand why the brackets work. What does exactly happen?

Is it that in
(...) * 4;

"..." is interpreted always part of an expression because of the outer expression.

With parentheses the expression is no longer an element of a block, so it can't be a statement, there is no longer a parsing ambiguity. You can't have a statement wrapped in parentheses.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.