The Go Programming Language Specification
Assignments
任务分两个阶段进行。一、索引的操作数
表达式和指针间接(包括隐式指针
选择器中的间接)在左边和表达式在
right 都按照通常的顺序进行评估。二、作业
按从左到右的顺序执行。
说明多个分配的常用示例是交换。例如,
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)
}
}
游乐场:https://play.golang.org/p/HcD9zq_7tqQ
输出:
7 42
42 7
7 42
42 7
使用隐式临时变量的一个语句多重赋值相当于(简写)两个使用显式临时变量的多重赋值语句。
您的斐波那契示例通过显式顺序和临时变量转换为:
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())
}
游乐场:https://play.golang.org/p/XFq-0wyNke9
输出:
1 1 2 3 5 8
1 1 2 3 5 8