Golang sort.Swap 方法

huangapple go评论75阅读模式
英文:

Golang sort.Swap Method

问题

这段代码是用于交换字符串切片中两个元素的位置。p[i], p[j] = p[j], p[i]这一行代码使用了Go语言的多重赋值特性,它的作用是将p[i]的值赋给p[j],同时将p[j]的值赋给p[i],实现了两个元素的位置交换。换句话说,它将索引为ij的两个元素进行了互换。这在排序算法中经常被使用,用于调整元素的顺序。

英文:

I am fairly new to Golang, although I have already written some lines of code. I was exploring the sorting options when I found this<sup>(src)</sup>:

func (p StringSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

I have no clue what is it going on there. Could someone explain to me what p[i], p[j] = p[j], p[i] is doing?

Thanks.

答案1

得分: 4

它做的就是它的名字所说的:交换第i和第j个元素。

这是一个赋值操作,更具体地说是一个元组赋值:

p[i], p[j] = p[j], p[i]

它给p[i]p[j]赋值,按顺序分别赋予它们的值是p[j]p[i]

赋值过程分为两个阶段。首先,左边的索引表达式和指针间接引用(包括选择器中的隐式指针间接引用)以及右边的表达式都按照通常的顺序进行求值。其次,赋值按照从左到右的顺序进行。

英文:

It does what its name says: it swaps the i<sup>th</sup> and j<sup>th</sup> elements.

It is an assignment, more specifically a tuple assignment:

p[i], p[j] = p[j], p[i]

It assigns values to p[i] and p[j], and the values that are assigned to them in order are p[j] and p[i].

> 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.

答案2

得分: 0

在Go语言中,我们不需要一个临时变量。它可以直接在一行中进行赋值操作:
p[i], p[j] = p[j], p[i]

这是Go语言中的一个奇迹之一。
享受吧!

英文:

here in golang, we dont need a tmp variable.
It will assign directly with line
p[i], p[j] = p[j], p[i]

it is one of miracles in golang
Enjoy!

huangapple
  • 本文由 发表于 2015年7月15日 17:15:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/31426232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定