eversor
eversor

Reputation: 3073

Golang sort.Swap Method

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(src):

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.

Upvotes: 0

Views: 636

Answers (2)

Vutuz
Vutuz

Reputation: 468

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!

Upvotes: 0

icza
icza

Reputation: 417867

It does what its name says: it swaps the ith and jth 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.

Upvotes: 4

Related Questions