gpt4 book ai didi

go - 在 Go 中为多个变量赋值

转载 作者:IT王子 更新时间:2023-10-29 00:38:38 24 4
gpt4 key购买 nike

我最近遇到了这个:

func main() {
x, y := 0, 1
x, y = y, x+y
fmt.Println(y)
}

我的想法是:

x, y = y, x+y

等同于:

x = y
y = x+y

最终值 x = 1, y = 2

但是我得到的最终值是x = 1, y = 1

这是为什么?

谢谢。

最佳答案

原来是这样specified :

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.

赋值首先计算右侧的所有表达式,然后将结果赋值给左侧的变量。

你的

x, y = y, x+y

基本等同于这个

tmp1 := y
tmp2 := x+y
x = tmp1
y = tmp2

您甚至可以使用这一事实在一行中交换 2 个变量,如下所示:

a, b = b, a

关于go - 在 Go 中为多个变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41314959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com