How to use Swapper in Golang?

Tuesday, March 3, 2020 • 2 minutes to read

Tutorialto-the-pointGolanggolangto-the-point

Swapper is a function defined in the reflect package. This function takes a slice and returns a swap function. This swap function takes 2 indexes as arguments and swaps the values at index position in the slice.

Function Definition

1func Swapper(slice interface{}) func(i, j int)

Let's try

 1package main
 2
 3import (
 4	"fmt"
 5	"reflect"
 6)
 7
 8func main() {
 9	s := []int{1, 2, 3}
10	fmt.Printf("Before swap: %v\n", s)
11
12	swapF := reflect.Swapper(s)
13
14	swapF(0, 1)
15
16	fmt.Printf("After 1 swap: %v\n", s)
17
18	swapF(0, 2)
19
20	fmt.Printf("After 2 swap: %v\n", s)
21}

Try it

Output

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

Swapper panics if the provided interface is not a slice.

panic: reflect: call of Swapper on <Type> Value

Reverse a slice using Swapper

Swap first element with last element, second element with second last and so on.

 1package main
 2
 3import (
 4	"fmt"
 5	"reflect"
 6)
 7
 8func main() {
 9	s := []int{1, 2, 3, 4, 5, 6, 7}
10
11	fmt.Printf("Before swap: %v\n", s)
12
13	swapF := reflect.Swapper(s)
14
15	for i := 0; i < len(s)/2; i++ {
16		swapF(i, len(s)-1-i)
17	}
18
19	fmt.Printf("After swap: %v\n", s)
20}
21

Try it

Output

Before swap: [1 2 3 4 5 6 7]
After swap: [7 6 5 4 3 2 1]

Use Swapper in Bubble sort

 1package main
 2
 3import (
 4	"fmt"
 5	"reflect"
 6)
 7
 8func main() {
 9	s := []int{1, 2, 6, 3, 8, 0, 7, 9, 5, 4}
10
11	fmt.Printf("Before swapper: %v\n", s)
12
13	swapF := reflect.Swapper(s)
14
15	for i := 0; i < len(s)-1; i++ {
16		for j := i + 1; j < len(s); j++ {
17			if s[i] > s[j] {
18				swapF(i, j)
19			}
20		}
21	}
22
23	fmt.Printf("After swapper: %v\n", s)
24}

Output

Before swapper: [1 2 6 3 8 0 7 9 5 4]
After swapper: [0 1 2 3 4 5 6 7 8 9]

Tutorialto-the-pointGolanggolangto-the-point

PreviousConvert String to Int and Int to String in Golang