go深度拷贝msgpack版
Posted littlelee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go深度拷贝msgpack版相关的知识,希望对你有一定的参考价值。
通关msgpack的序列化和反序列化进行深度拷贝
package main import ( "fmt" "reflect" "github.com/vmihailenco/msgpack" ) 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 NewSkill() *Skill { return &Skill{1, 1} } func NewEquip() *Equip { return &Equip{1, 1} } 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 MsgPackDeepCopy(dst, src interface{}) error { b, err := msgpack.Marshal(src) if err != nil { return err } err = msgpack.Unmarshal(b, dst) if err != nil { return err } return nil } func main() { p1 := NewPlayer() p2 := new(Player) MsgPackDeepCopy(p2, p1) fmt.Println(reflect.DeepEqual(p1, p2)) } //output //true //goos: windows //goarch: amd64 //pkg: game.lab/go-deepcopy/src/msgpack //100000 20220 ns/op //PASS // 性能测试 func BenchmarkMsgPack(b *testing.B) { p1 := NewPlayer() p2 := new(Player) for i:=0 ; i<b.N ; i++ { MsgPackDeepCopy(p2, p1) } }
以上是关于go深度拷贝msgpack版的主要内容,如果未能解决你的问题,请参考以下文章
[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础
解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段