Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Copy()函数用于将源的内容复制到目标中,直到目标已填充或源已用完为止。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function takes two parameters of Slice or Array type. And dst and src must have the same element type.
Return Value: This function returns the number of elements copied.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func Copy(dst, src Value) int
输出:
// 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)
}
示例 2:
Number of element Copied : 3
Source : [10 20 32]
destination : [100 20 32]
输出:
// 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)
}