How do you swap two values in Go? Provide a few examples.

In Go, you can swap two values using multiple approaches. Here are a few examples of how to swap two values:

  1. Using a Temporary Variable:
package main

import "fmt"

func swapWithTemp(a, b int) (int, int) {
    temp := a
    a = b
    b = temp
    return a, b
}

func main() {
    x, y := 10, 20
    fmt.Println("Before swap:", x, y)
    x, y = swapWithTemp(x, y)
    fmt.Println("After swap:", x, y)
}
  1. Using Arithmetic Operations (Addition and Subtraction):
package main

import "fmt"

func swapWithArithmetic(a, b int) (int, int) {
    a = a + b
    b = a - b
    a = a - b
    return a, b
}

func main() {
    x, y := 10, 20
    fmt.Println("Before swap:", x, y)
    x, y = swapWithArithmetic(x, y)
    fmt.Println("After swap:", x, y)
}
  1. Using Bitwise XOR:
package main

import "fmt"

func swapWithXOR(a, b int) (int, int) {
    a = a ^ b
    b = a ^ b
    a = a ^ b
    return a, b
}

func main() {
    x, y := 10, 20
    fmt.Println("Before swap:", x, y)
    x, y = swapWithXOR(x, y)
    fmt.Println("After swap:", x, y)
}

All three examples will produce the same output:

Before swap: 10 20
After swap: 20 10

In each approach, the two values x and y are swapped without using any additional temporary variables. You can choose any of these methods based on your preference and specific use case. The Go compiler and runtime are optimized, so the performance difference between these methods is generally negligible.

error: Content is protected !!