go中的深度拷贝direct版

Posted littlelee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go中的深度拷贝direct版相关的知识,希望对你有一定的参考价值。

4.给每个结构写拷贝函数(效率最高)

package main

import (
	"fmt"
	"reflect"
)

type (
	Player struct {
		Id     int
		Level  int
		Heroes map[int]*Hero
		Equips []*Equip
	}

	Hero struct {
		Id     int
		Level  int
		Skills []*Skill
	}

	Equip struct {
		Id    int
		Level int
	}

	Skill struct {
		Id    int
		Level int
	}
)

func NewHero() *Hero {
	return &Hero{
		Id:     1,
		Level:  1,
		Skills: append([]*Skill{NewSkill()}, NewSkill(), NewSkill()),
	}
}

func (self *Player) deepCopy(dst **Player)  {
	p := &Player{}
	p.Id = self.Id
	p.Level = self.Level
	p.Heroes = make(map[int]*Hero)
	for key, value := range self.Heroes {
		p.Heroes[key] = value.deepCopy()
	}

	for _, v := range self.Equips {
		p.Equips = append(p.Equips, v.deepCopy())
	}
	*dst = p
}

func (self *Hero) deepCopy() *Hero  {
	pHero := &Hero{}
	pHero.Id = self.Id
	pHero.Level = self.Level
	for _, v := range self.Skills {
		pHero.Skills = append(pHero.Skills, v.deepCopy())
	}
	return pHero
}


func NewSkill() *Skill {
	return &Skill{1, 1}
}

func (self *Skill) deepCopy() *Skill  {
	return &Skill{self.Id, self.Level}
}

func NewEquip() *Equip {
	return &Equip{1, 1}
}

func (self *Equip) deepCopy() *Equip  {
	return &Equip{self.Id, self.Level}
}

func NewPlayer() *Player {
	return &Player{
		Id:     1,
		Level:  1,
		Heroes: map[int]*Hero{1: NewHero(), 2: NewHero(), 3: NewHero()},
		Equips: append([]*Equip{NewEquip()}, NewEquip(), NewEquip()),
	}
}

func (self *Hero) Print() {
	fmt.Printf("hero Id=%d, Level=%d
", self.Id, self.Level)
	for _, v := range self.Skills {
		fmt.Printf("%v
", *v)
	}
}

func (self *Player) Print() {
	fmt.Printf("player Id=%d, Level=%d
", self.Id, self.Level)
	for _, v := range self.Heroes {
		v.Print()
	}

	for _, v := range self.Equips {
		fmt.Printf("%+v
", *v)
	}
}

func main() {
	p1 := NewPlayer()
	p2 := &Player{}
	p1.deepCopy(&p2)
	fmt.Println(reflect.DeepEqual(p1, p2))
}

output:
	true

// 性能测试
func BenchmarkGob(b *testing.B) {
	p1 := NewPlayer()
	p2 := &Player{}
	for i:=0 ; i<b.N ; i++ {
		p1.deepCopy(&p2)
	}
}

goos: windows
goarch: amd64
pkg: game.lab/go-deepcopy/src/direct
1000000	      1246 ns/op
PASS

  

以上是关于go中的深度拷贝direct版的主要内容,如果未能解决你的问题,请参考以下文章

golang深度拷贝reflect版

Go切片数组深度解析

go map and slice 2021-10-08

26.Qt Quick QML-RotationAnimationPathAnimationSmoothedAnimationBehaviorPauseAnimationSequential(代码片段

Go语言中的零拷贝优化,值得大家收藏

算法热门:深度拷贝带随机指针的链表(LeetCode 138)