Golang reflect.Copy() 函数及示例

Golang reflect.Copy() 函数及示例

Go语言提供了运行时反射的内置支持,使程序能够使用 reflect 包操作具有任意类型的对象。Golang 中的 reflect.Copy() 函数用于将源的内容复制到目标,直到目标已填满或源已耗尽。要使用此函数,需要在程序中导入 reflect 包。

语法:

func Copy(dst, src Value) int

参数:

此函数接受 Slice 或 Array 类型的两个参数。dst 和 src 必须具有相同的元素类型。

返回值:

该函数返回所复制的元素数。

下面的示例说明了在 Golang 中使用上述方法:

示例1:

// Golang程序示例
// reflect.Copy () Function
package main

import (
    "fmt"
    "reflect"
)

// 主函数
func main() {

    // 源
    src := reflect.ValueOf([]int{10, 20, 32})

   /*确保目标空间大于src*/
    // 目的地
    dest := reflect.ValueOf([]int{1, 2, 3})

    // 用于拷贝的 Copy() 函数并返回所拷贝的元素树
    cnt := reflect.Copy(dest, src)
    data := dest.Interface().([]int)
    data[0] = 100

    // 打印值
    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程序示例
// reflect.Copy () Function
package main

import (
    "fmt"
    "reflect"
)

// 包含两个 int 值的结构体
type temp struct {
    A0 []int
    A1 []int
}

// 主函数
func main() {

    var val temp

    // 源
    val.A0 = append(val.A0, []int{1, 2, 3,
                                    4, 5, 6, 7, 8, 9}...)

    // 目的地
    val.A1 = append(val.A1, 9, 8, 7, 6)

    // 用于拷贝的 Copy() 函数并返回所拷贝的元素数
    var n = reflect.Copy(reflect.ValueOf(val.A0), 
                            reflect.ValueOf(val.A1))

    // 打印值
    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]}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程