广告
返回顶部
首页 > 资讯 > 后端开发 > GO >Go语言深度拷贝工具deepcopy的使用教程
  • 909
分享到

Go语言深度拷贝工具deepcopy的使用教程

2024-04-02 19:04:59 909人浏览 薄情痞子
摘要

目录实现原理分析基本使用拷贝切片拷贝map今天给大家推荐的工具是deepcopy,一个可以对指针、接口、切片、结构体、Map都能进行深拷贝的工具。在Go中需要对一个变量进行拷贝时分浅

今天给大家推荐的工具是deepcopy,一个可以对指针、接口、切片、结构体、Map都能进行深拷贝的工具。在Go中需要对一个变量进行拷贝时分浅拷贝和深拷贝。浅拷贝就是拷贝后就是无论改变新值还是原值都对对另一个产生影响,比如切片。而深拷贝则是将目标值完全拷贝一份,消除这种影响。

实现原理分析

深拷贝的实现原理本质上是通过反射实现。通过将源对象转换成接口,再对接口通过反射判断其类型,进而进行深度拷贝。如下就是该包的完全实现:

package deepcopy

import (
	"reflect"
	"time"
)

// Interface for delegating copy process to type
type Interface interface {
	DeepCopy() interface{}
}

// Iface is an alias to Copy; this exists for backwards compatibility reasons.
func Iface(iface interface{}) interface{} {
	return Copy(iface)
}

// Copy creates a deep copy of whatever is passed to it and returns the copy
// in an interface{}.  The returned value will need to be asserted to the
// correct type.
func Copy(src interface{}) interface{} {
	if src == nil {
		return nil
	}

	// Make the interface a reflect.Value
	original := reflect.ValueOf(src)

	// Make a copy of the same type as the original.
	cpy := reflect.New(original.Type()).Elem()

	// Recursively copy the original.
	copyRecursive(original, cpy)

	// Return the copy as an interface.
	return cpy.Interface()
}

// copyRecursive does the actual copying of the interface. It currently has
// limited support for what it can handle. Add as needed.
func copyRecursive(original, cpy reflect.Value) {
	// check for implement deepcopy.Interface
	if original.CanInterface() {
		if copier, ok := original.Interface().(Interface); ok {
			cpy.Set(reflect.ValueOf(copier.DeepCopy()))
			return
		}
	}

	// handle according to original's Kind
	switch original.Kind() {
	case reflect.Ptr:
		// Get the actual value being pointed to.
		originalValue := original.Elem()

		// if  it isn't valid, return.
		if !originalValue.IsValid() {
			return
		}
		cpy.Set(reflect.New(originalValue.Type()))
		copyRecursive(originalValue, cpy.Elem())

	case reflect.Interface:
		// If this is a nil, don't do anything
		if original.IsNil() {
			return
		}
		// Get the value for the interface, not the pointer.
		originalValue := original.Elem()

		// Get the value by calling Elem().
		copyValue := reflect.New(originalValue.Type()).Elem()
		copyRecursive(originalValue, copyValue)
		cpy.Set(copyValue)

	case reflect.Struct:
		t, ok := original.Interface().(time.Time)
		if ok {
			cpy.Set(reflect.ValueOf(t))
			return
		}
		// Go through each field of the struct and copy it.
		for i := 0; i < original.NumField(); i++ {
			// The Type's StructField for a given field is checked to see if StructField.PkgPath
			// is set to determine if the field is exported or not because CanSet() returns false
			// for settable fields.  I'm not sure why.  -mohae
			if original.Type().Field(i).PkgPath != "" {
				continue
			}
			copyRecursive(original.Field(i), cpy.Field(i))
		}

	case reflect.Slice:
		if original.IsNil() {
			return
		}
		// Make a new slice and copy each element.
		cpy.Set(reflect.MakeSlice(original.Type(), original.Len(), original.Cap()))
		for i := 0; i < original.Len(); i++ {
			copyRecursive(original.Index(i), cpy.Index(i))
		}

	case reflect.Map:
		if original.IsNil() {
			return
		}
		cpy.Set(reflect.MakeMap(original.Type()))
		for _, key := range original.MapKeys() {
			originalValue := original.Mapindex(key)
			copyValue := reflect.New(originalValue.Type()).Elem()
			copyRecursive(originalValue, copyValue)
			copyKey := Copy(key.Interface())
			cpy.SetMapIndex(reflect.ValueOf(copyKey), copyValue)
		}

	default:
		cpy.Set(original)
	}
}

基本使用

拷贝切片

	a := []int{1,2,3}
	dst := deepcopy.Copy(a)
	a1 := dst.([]int)
	a1[0] = 2
	fmt.Println(a, a1) //a:[1 2 3] a1:[2 2 3]

拷贝map

	a := make(map[string]int)
	a["k1"] = 1
	a["k2"] = 2
	a["k3"] = 3
	dst := deepcopy.Copy(a)
	a1 := dst.(map[string]int)
	a1["k1"] = 10
	fmt.Println(a, a1) //a:map[k1:1 k2:2 k3:3] a1:map[k1:10 k2:2 k3:3]

更多项目详情请查看如下链接。

开源项目地址:https://GitHub.com/mohae/deepcopy

到此这篇关于Go语言深度拷贝工具deepcopy的使用教程的文章就介绍到这了,更多相关Go深度拷贝deepcopy内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

您可能感兴趣的文档:

--结束END--

本文标题: Go语言深度拷贝工具deepcopy的使用教程

本文链接: https://www.lsjlt.com/news/121197.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Go语言深度拷贝工具deepcopy的使用教程
    目录实现原理分析基本使用拷贝切片拷贝map今天给大家推荐的工具是deepcopy,一个可以对指针、接口、切片、结构体、Map都能进行深拷贝的工具。在Go中需要对一个变量进行拷贝时分浅...
    99+
    2022-11-11
  • Go语言官方依赖注入工具Wire的使用教程
    目录1. 前言2. 依赖注入(DI)是什么3. Wire Come3.1 简介3.2 快速使用3.3 基础概念4. Wire使用实践4.1 基础使用4.2 高级特性4.3 高阶使用5...
    99+
    2022-11-11
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作