Skip to content
Related Articles

Related Articles

Improve Article

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:




// Golang program to illustrate
// reflect.Swapper() Function 
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function 
func main() {
   
    // Slice 
    src := []int{1, 2, 3, 4, 5}
  
    fmt.Printf("Before swap: %v\n", src)
       
    // Swapper() function is used
    // to swaps the elements in 
    // the provided slice
    swapF := reflect.Swapper(src) 
  
    swapF(2, 4)
       
    // printing the values
    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




// Golang program to illustrate
// reflect.Swapper() Function 
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function 
func main() {
   
    // Slice 
    src := []int{1, 2, 3, 4, 5, 6, 7}
  
    fmt.Printf("Original Slice: %v\n", src)
       
    // Swapper() function is used
    // to swaps the elements in 
    // the provided slice
    swapF := reflect.Swapper(src)
  
    for i := 0; i < len(src)/2; i++ {
        swapF(i, len(src)-1-i)
    }
       
    // printing the values
    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




// Golang program to illustrate
// reflect.Swapper() Function 
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function 
func main() {
   
    // Slice 
    src := []int{1, 2, 6, 3, 8, 0, 7, 9, 5, 4, 42, 1, 3, 4, 3}
  
    fmt.Printf("Original Slice: %v\n", src)
       
    // Swapper() function is used
    // to swaps the elements in 
    //the provided slice
    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)
            }
        }
    }
       
    //printing the values
    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]



My Personal Notes arrow_drop_up
Recommended Articles
Page :