Google News
logo
Golang - Interview Questions
Swap the values of two variables without a temporary variable.
Implement swap() which swaps the value of two variables without using a third variable.
 
Example : 
package main

import "fmt"

func main() {
   fmt.Println(swap())
}

func swap() []int {
      a, b := 15, 10
   b, a = a, b
   return []int{a, b}
}

Output :

[10 15]

 

While this may be tricky in other languages, Go makes it easy.

We can simply include the statement b, a = a, b, what data the variable references without engaging with either value.

Advertisement