Why abc printed?

Hello,
In the following code, why abc printed?

fn main() {
    let _a = if true { "abc" } else { "xy" };
    println!("{}", _a);
}

Thank you.

Are you having trouble understanding what if true means, or something about underscore-prefixed variables?

3 Likes

What else would you expect to be printed?

1 Like

if … { … } else { … } is an expression (an IfExpression) that serves the same purpose as the ternary operator (… ? … : …) in many other languages.

See Ternary_conditional_operator#Conditional_assignment on Wikipedia.

2 Likes

Hello,
Thank you so much for your reply.
This print abc, because if true is always true?

1 Like

Well, true is always true. And if condition { … } else { … } where the condition is true, will evaluate to the first block, and not the second.

I.e. it will execute the first block and return its result the whole IfExpression will evaluate to what the first block evaluates to.

2 Likes

For further introduction to how if in Rust works, especially when used with let, see also:

Using if in a let Statement – if Expressions – Control Flow – The Rust Programming Language

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.