英文:
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
是的。根据语言规范:
赋值过程分为两个阶段。首先,左侧的索引表达式和指针间接引用(包括选择器中的隐式指针间接引用)以及右侧的表达式按照通常的顺序进行求值。其次,按照从左到右的顺序进行赋值操作。
所以在你的例子中,child
和 child.child
将首先被求值,然后分别赋值给 parent
和 child
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论