當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang reflect.Swapper()用法及代碼示例

Go語言提供了運行時反射的內置支持實現,並允許程序借助反射包來操縱任意類型的對象。 Golang中的reflect.Swapper()函數用於交換提供的切片中的元素。要訪問此函數,需要在程序中導入反射包。

用法:
func Swapper(slice interface{}) func(i, j int)

參數:此函數采用“切片”類型的一個參數。

返回值:此函數返回交換的片。

以下示例說明了以上方法在Golang中的用法:



範例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) 
}

輸出:

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

範例2:使用Swapper()函數反轉切片

// 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) 
}

輸出:

Original Slice:[1 2 3 4 5 6 7]
Reversed Slice:[7 6 5 4 3 2 1]

範例3:使用Swapper()函數對切片進行排序

// 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) 
}

輸出:

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]



相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 reflect.Swapper() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。