多重赋值是否有顺序?

huangapple go评论111阅读模式
英文:

Does multiple assignment have order?

问题

我知道Golang支持多重赋值,例如:

a, b = c, d

我想知道赋值是否按照从左到右的顺序进行。例如,如果我在处理树结构:

parent, child = child, child.child

这样的赋值是否确保parent和child都在树中向下移动了一层?

英文:

I know golang supports multiple assignment, for instance,

a, b = c, d

I want to know if the assignment following the left->right order? For instance, if I play with trees:

parent, child = child, child.child

Does it guarantee both parent and child are assigned one level deeper in the tree?

答案1

得分: 20

是的。根据语言规范

赋值过程分为两个阶段。首先,左侧的索引表达式和指针间接引用(包括选择器中的隐式指针间接引用)以及右侧的表达式按照通常的顺序进行求值。其次,按照从左到右的顺序进行赋值操作。

所以在你的例子中,childchild.child 将首先被求值,然后分别赋值给 parentchild

英文:

Yes. From the language spec:

> The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.

So in your example, child and child.child will be evaluated first, then assigned to parent and child respectively.

huangapple
  • 本文由 发表于 2017年8月6日 06:33:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/45526926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定