golang多重赋值评估

Jer*_*obs 3 go

我对多重分配的概念感到困惑。鉴于以下代码:

func fibonacci() func() int {
    current, next := 0, 1
    return func() int {
        current, next = next, current+next
        return current
    }
}
Run Code Online (Sandbox Code Playgroud)

鉴于两个变量都出现在赋值的左侧和右侧,如何评估赋值?

pet*_*rSO 6

Go 编程语言规范

作业

任务分两个阶段进行。首先,左边的索引表达式和指针间接(包括选择器中的隐式指针间接)的操作数和右边的表达式都按通常的顺序计算。其次,分配按从左到右的顺序进行。


说明多重赋值的常用例子是交换。例如,

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场:https : //play.golang.org/p/HcD9zq_7tqQ

输出:

7 42
42 7

7 42
42 7
Run Code Online (Sandbox Code Playgroud)

使用隐式临时变量的 one 语句多重赋值等效于(简写)两个使用显式临时变量的多重赋值语句。


您的斐波那契示例使用显式顺序和临时变量转换为:

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())
}
Run Code Online (Sandbox Code Playgroud)

游乐场:https : //play.golang.org/p/XFq-0wyNke9

输出:

1 1 2 3 5 8
1 1 2 3 5 8
Run Code Online (Sandbox Code Playgroud)