Skip to content

Commit 9687a3f

Browse files
fiveseven-lambdatraviscross
authored andcommitted
Clarify operand evaluation order in compound assignment
...with primitive vs generic types.
1 parent 4d77198 commit 9687a3f

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/expressions/operator-expr.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -903,12 +903,16 @@ r[expr.compound-assign.operand-order]
903903
Evaluation of compound assignment expressions depends on the types of the operators.
904904

905905
r[expr.compound-assign.primitive-order]
906-
If both types are primitives, then the modifying operand will be evaluated first followed by the assigned operand.
906+
If both types are primitives and the expression is non-generic (i.e., directly uses concrete types), then the modifying operand will be evaluated first followed by the assigned operand.
907907
It will then set the value of the assigned operand's place to the value of performing the operation of the operator with the values of the assigned operand and modifying operand.
908908

909909
> [!NOTE]
910910
> This is different than other expressions in that the right operand is evaluated before the left one.
911911
912+
> [!NOTE]
913+
> This right-before-left evaluation only occurs in non-generic code involving primitive types.
914+
> In all other cases---including generic contexts or non-primitive types---the expression is desugared into a trait method call, and operands are evaluated left to right.
915+
912916
r[expr.compound-assign.trait]
913917
Otherwise, this expression is syntactic sugar for calling the function of the overloading compound assignment trait of the operator (see the table earlier in this chapter).
914918
A mutable borrow of the assigned operand is automatically taken.
@@ -937,9 +941,10 @@ r[expr.compound-assign.result]
937941
Like assignment expressions, compound assignment expressions always produce [the unit value][unit].
938942

939943
> [!WARNING]
940-
> The evaluation order of operands swaps depending on the types of the operands:
941-
> with primitive types the right-hand side will get evaluated first, while with non-primitive types the left-hand side will get evaluated first.
942-
> Try not to write code that depends on the evaluation order of operands in compound assignment expressions.
944+
> The evaluation order of operands varies depending on how the expression is desugared.
945+
> Non-generic primitive assignments may evaluate the right-hand side first.
946+
> Trait-based assignments, including all generic cases, evaluate left-hand side first.
947+
> Avoid writing code that depends on operand evaluation order.
943948
> See [this test] for an example of using this dependency.
944949
945950
[`Try`]: core::ops::Try

0 commit comments

Comments
 (0)