reflect.Swapper() Function in Golang with Examples
Last Updated :
28 Apr, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Swapper() Function in Golang is used to swaps the elements in the provided slice. To access this function, one needs to imports the reflect package in the program.
Syntax:
func Swapper(slice interface{}) func(i, j int)
Parameters: This function takes one parameters of Slice type.
Return Value: This function returns the swapped slice.
Below examples illustrate the use of above method in Golang:
Example 1:
package main
import (
"fmt"
"reflect"
)
func main() {
src := [] int {1, 2, 3, 4, 5}
fmt.Printf( "Before swap: %v\n" , src)
swapF := reflect.Swapper(src)
swapF(2, 4)
fmt.Printf( "After swap: %v\n" , src)
}
|
Output:
Before swap: [1 2 3 4 5]
After swap: [1 2 5 4 3]
Example 2: Reversing a slice using Swapper() function
package main
import (
"fmt"
"reflect"
)
func main() {
src := [] int {1, 2, 3, 4, 5, 6, 7}
fmt.Printf( "Original Slice: %v\n" , src)
swapF := reflect.Swapper(src)
for i := 0; i < len(src)/2; i++ {
swapF(i, len(src)-1-i)
}
fmt.Printf( "Reversed Slice: %v\n" , src)
}
|
Output:
Original Slice: [1 2 3 4 5 6 7]
Reversed Slice: [7 6 5 4 3 2 1]
Example 3: Sorting of a slice using Swapper() function
package main
import (
"fmt"
"reflect"
)
func main() {
src := [] int {1, 2, 6, 3, 8, 0, 7, 9, 5, 4, 42, 1, 3, 4, 3}
fmt.Printf( "Original Slice: %v\n" , src)
swapF := reflect.Swapper(src)
for i := 0; i < len(src)-1; i++ {
for j := i + 1; j < len(src); j++ {
if src[i] > src[j] {
swapF(i, j)
}
}
}
fmt.Printf( "Sorted Slice: %v\n" , src)
}
|
Output:
Original Slice: [1 2 6 3 8 0 7 9 5 4 42 1 3 4 3]
Sorted Slice: [0 1 1 2 3 3 3 4 4 5 6 7 8 9 42]
Share your thoughts in the comments
Please Login to comment...