Best way to swap variable values in Go?

There is a function called Swapper which takes a slice and returns a swap function. This swap function takes 2 indexes and swap the index values in the slice.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    s := []int{1, 2, 3}

    fmt.Printf("Before swap: %v\n", s)

    swapF := reflect.Swapper(s)

    swapF(0, 1)

    fmt.Printf("After swap: %v\n", s)
}

Try it

Output

Before swap: [1 2 3]
After swap: [2 1 3]

Yes, you can swap values like python.

a, b := 0, 1
fmt.Printf("Before swap a = %v, b = %v\n", a, b)

b, a = a, b
fmt.Printf("After swap a = %v, b = %v\n", a, b)

Output

Before swap a = 0, b = 1
After swap a = 1, b = 0

Yes, it is possible. Assuming a and b have the same type, the example provided will work just fine. For example:

a, b := "second", "first"
fmt.Println(a, b) // Prints "second first"
b, a = a, b
fmt.Println(a, b) // Prints "first second"

Run sample on the playground

This is both legal and idiomatic, so there's no need to use an intermediary buffer.


Yes you can swap by using

a, b = b, a

So if a = 1 and b= 2, then after executing

a , b = b, a

you get a = 2 and b = 1

Also, if you write

a, b, a = b, a, b

then it results b = 1 and a = 2


Yes it is possible to swap elements using multi-value assignments:

i := []int{1, 2, 3, 4}
fmt.Println(i)

i[0], i[1] = i[1], i[0]
fmt.Println(i)

a, b := 1, 2
fmt.Println(a, b)

a, b = b, a // note the lack of ':' since no new variables are being created
fmt.Println(a, b)

Output:

[1 2 3 4]
[2 1 3 4]
1 2
2 1

Example: https://play.golang.org/p/sopFxCqwM1

More details here: https://golang.org/ref/spec#Assignments

Tags:

Slice

Swap

Go