I'm trying to wrap my head around if-let expressions. I know what it does but I can't find the rationale behind some details.
The first detail is the use of the assignment operator instead of the equality operator, and the second one is the placement of the operands.
For example:
let a = Some(5);
if let Some(i) = a {
println!("Hello, {}!", i);
}
In my head its more "legible" this way:
if let Some(i) == a {
println!("Hello, {}!", i);
}
Or even better:
if let a == Some(i) {
println!("Hello, {}!", i);
}
Could someone please help me understand the rationale behind this?
The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.
The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not.
The simple assignment operator ( = ) is used to assign a value to a variable.
Assignment expressions allow you to assign and return a value in the same expression. For example, if you want to assign to a variable and print its value, then you typically do something like this: >>> >>> walrus = False >>> print(walrus) False.
The Rust syntax is
let Some(i) = a
because we are creating a new variable i
and initializing it with the wrapped value in a
. The operator =
is for creating new variables. You have a pattern on the left hand side, and an expression on the right. All variables on the left, in the pattern, get initialized based on the corresponding values in the expression on the right.
The comparison operator ==
would not make sense here. To say
let Some(i) == a
would seem to return whether the expression
let Some(i)
is equal to the expression
a
When using ==
you expect the left and right hand sides to be complete expressions, that already have values, then you return whether they are equal. But that is not what we are doing in an if-let. When we use if-let we are creating a new variable. ==
only makes sense when the expressions on both sides of it can be evaluated.
Similarly, the expression
let a == Some(i)
is quite odd, because a
already exists. We certainly are not creating a new variable a
. And the same argument against using ==
as before applies, since i
does not yet exist.
In summary we use =
when creating a new variable and ==
for testing the equality of expressions (which if they have variables in them, such variables must already exist).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With