Go 戈朗多项任务评估
我对多重指派的概念感到困惑。给定以下代码:Go 戈朗多项任务评估,go,Go,我对多重指派的概念感到困惑。给定以下代码: func fibonacci() func() int { current, next := 0, 1 return func() int { current, next = next, current+next return current } } 鉴于两个变量都出现在赋值的左侧和右侧,赋值是如何计算的?来自: 转让分两个阶段进行。首先,左侧的索引表达式和指针间接(包括选择器中的隐式指针间接)
func fibonacci() func() int {
current, next := 0, 1
return func() int {
current, next = next, current+next
return current
}
}
鉴于两个变量都出现在赋值的左侧和右侧,赋值是如何计算的?来自:
转让分两个阶段进行。首先,左侧的索引表达式和指针间接(包括选择器中的隐式指针间接)的操作数和右侧的表达式都按通常的顺序求值。其次,作业按从左到右的顺序进行
顺序在语言规范中定义
在包级别,初始化依赖关系确定变量声明中各个初始化表达式的求值顺序。否则,在计算表达式、赋值或返回语句的操作数时,所有函数调用、方法调用和通信操作都将按从左到右的词法顺序进行计算
这是一个复杂评估顺序的好例子
y[f()],ok=g(h(),i()+x[j()],
赋值分两个阶段进行。首先,索引的操作数
表达式和指针间接(包括隐式指针
选择器中的间接项)和
好的,所有的作业都按照通常的顺序进行评估。第二,作业
按从左到右的顺序执行
说明多个赋值的常见示例是交换。例如
package main
import "fmt"
func main() {
{
i, j := 7, 42
fmt.Println(i, j)
// swap i and j - implicit temporaries
i, j = j, i
fmt.Println(i, j)
}
fmt.Println()
{
i, j := 7, 42
fmt.Println(i, j)
// swap i and j - explicit temporaries
ti, tj := i, j
i, j = tj, ti
fmt.Println(i, j)
}
}
游乐场:
输出:
7 42
42 7
7 42
42 7
1 1 2 3 5 8
1 1 2 3 5 8
使用隐式临时变量的单语句多重赋值相当于使用显式临时变量的两个多重赋值语句(简称)
您的斐波那契示例使用显式顺序和临时变量转换为:
package main
import "fmt"
func fibonacciMultiple() func() int {
current, next := 0, 1
return func() int {
current, next = next, current+next
return current
}
}
func fibonacciSingle() func() int {
current, next := 0, 1
return func() int {
// current, next = next, current+next
// first phase, evaluation, left-to-right
t1 := next
t2 := current + next
// second phase, assignmemt, left-to-right
current = t1
next = t2
return current
}
}
func main() {
m := fibonacciMultiple()
fmt.Println(m(), m(), m(), m(), m(), m())
s := fibonacciSingle()
fmt.Println(s(), s(), s(), s(), s(), s())
}
游乐场:
输出:
7 42
42 7
7 42
42 7
1 1 2 3 5 8
1 1 2 3 5 8
但在当前+下一步中使用的是“当前”的哪个值?在为其分配“下一步”之前还是之后?@JeroenJacobs:只有一个current
的值可在其中使用。所有操作数求值后才进行分配。