Best way to swap variable values in Go?
Asked Answered
B

5

35

Is it possible to swap elements like in python?

a,b = b,a

or do we have to use:

temp = a
a = b
b = temp
Bag answered 25/7, 2016 at 15:7 Comment(0)
A
79

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.

Abyssal answered 25/7, 2016 at 15:13 Comment(0)
E
25

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

Extract answered 25/7, 2016 at 15:13 Comment(0)
S
3

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

Stone answered 12/1, 2021 at 6:31 Comment(0)
C
2

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
Crine answered 1/3, 2020 at 16:55 Comment(0)
W
0

you can use ^ option like this...

func swap(nums []int, i, j int) {
    nums[i] ^= nums[j]
    nums[j] ^= nums[i]
    nums[i] ^= nums[j]
}
Wireman answered 12/9, 2021 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.