Hello,
In the following code, why abc
printed?
fn main() {
let _a = if true { "abc" } else { "xy" };
println!("{}", _a);
}
Thank you.
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?
What else would you expect to be printed?
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.
Hello,
Thank you so much for your reply.
This print abc
, because if true
is always true?
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.
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
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.