dongnigeng1295 2018-06-03 15:13
浏览 1053
已采纳

golang逗号分隔的表达式

In go docs there is a shuffle example (link)

I've added some output to it as follows:

package main

import (
    "fmt"
    "math/rand"
    "strings"
)

func main() {
    words := strings.Fields("ink runs from the corners of my mouth")
    fmt.Println(words)
    rand.Shuffle(len(words), func(i, j int) {
        fmt.Println("Before:", i, j, words[i])
        words[i], words[j] = words[j], words[i]
        fmt.Println("After:", i, j, words[i])

    })
    fmt.Println(words)
}

What I would like to understand is the line that has:

words[i], words[j] = words[j], words[i]

And specifically why the output before and after that statement is different. How is this evaluated? Thanks.

  • 写回答

1条回答 默认 最新

  • dongtang5776 2018-06-03 15:18
    关注

    The Go Programming Language Specification

    Assignments

    A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables. There are two forms. In the first, the right hand operand is a single multi-valued expression such as a function call, a channel or map operation, or a type assertion. The number of operands on the left hand side must match the number of values. For instance, if f is a function returning two values,

    x, y = f()
    

    assigns the first value to x and the second to y. In the second form, the number of operands on the left must equal the number of expressions on the right, each of which must be single-valued, and the nth expression on the right is assigned to the nth operand on the left:

    one, two, three = '一', '二', '三'
    

    words[i], words[j] = words[j], words[i] is the second form of a Go tuple assignment. The values of words[i]and words[j] are swapped.

    words[i], words[j] = words[j], words[i]

    becomes:

    // on the left
    tj := words[j]
    ti := words[i]
    // on the right
    words[i] = tj
    words[j] = ti
    

    simplify:

    t := words[i]
    words[i] = words[j]
    words[j] = t
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器