30

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
Sam Whited
  • 6,880
  • 2
  • 31
  • 37
Nicky Feller
  • 3,539
  • 9
  • 37
  • 54

5 Answers5

72

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.

Sam Whited
  • 6,880
  • 2
  • 31
  • 37
23

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

Sam Whited
  • 6,880
  • 2
  • 31
  • 37
abhink
  • 8,740
  • 1
  • 36
  • 48
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

Shivani Singhal
  • 315
  • 1
  • 10
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
Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45
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]
}
S.B
  • 13,077
  • 10
  • 22
  • 49
  • 3
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 12 '21 at 16:31