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


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

Go語言提供了運行時反射的內置支持實現,並允許程序借助反射包來操縱任意類型的對象。 Golang中的reflect.Copy()函數用於將源的內容複製到目標中,直到填充了目標或耗盡了源為止。要訪問此函數,需要在程序中導入反射包。

用法:
func Copy(dst, src Value) int

參數:此函數采用切片或數組類型的兩個參數。 dst和src必須具有相同的元素類型。

返回值:此函數返回複製的元素數。

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



範例1:

// Golang program to illustrate 
// reflect.Copy() Function  
  
package main 
  
import ( 
    "fmt"
    "reflect"
) 
  
// Main function  
func main() { 
  
    // Source  
    src:= reflect.ValueOf([]int{10, 20, 32}) 
      
    /* make sure the dest space is larger than src */
    // destination  
    dest:= reflect.ValueOf([]int{1, 2, 3}) 
      
    // To copy Copy() function is used 
    // and it returns the number of  
    // elements copied 
    cnt:= reflect.Copy(dest, src) 
    data:= dest.Interface().([]int) 
    data[0] = 100 
      
    // printing the values 
    fmt.Println("Number of element Copied:", cnt) 
    fmt.Println("Source:", src) 
    fmt.Println("destination:", dest) 
}

輸出:

Number of element Copied:3
Source:[10 20 32]
destination:[100 20 32]

範例2:

// Golang program to illustrate 
// reflect.Copy() Function  
  
package main 
  
import ( 
    "fmt"
    "reflect"
) 
  
// Struct with two int value 
type temp struct { 
    A0 []int
    A1 []int
} 
  
// Main function  
func main() { 
      
    var val temp 
      
    // Source  
    val.A0 = append(val.A0, []int{1, 2, 3, 
                    4, 5, 6, 7, 8, 9}...) 
      
    // destination  
    val.A1 = append(val.A1, 9, 8, 7, 6) 
      
    // To copy Copy() function is used 
    // and it returns the number of  
    // elements copied 
    var n = reflect.Copy(reflect.ValueOf(val.A0),  
                        reflect.ValueOf(val.A1)) 
      
    // printing the values 
    fmt.Println("Number of element Copied:", n) 
    fmt.Println("{Source, destination}:", val) 
      
}

輸出:

Number of element Copied:4
{Source, destination}:{[9 8 7 6 5 6 7 8 9] [9 8 7 6]}



相關用法


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