go深度拷贝gob版
作者:互联网
通过gob的序列化和反序列化进行深度拷贝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
package main
import (
"bytes"
"encoding/gob"
"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 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 GobDeepCopy(dst, src interface {}) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(src); err != nil {
return err
}
return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst)
}
func main() {
p1 := NewPlayer()
p2 := new(Player)
GobDeepCopy(p2, p1)
fmt.Println(reflect.DeepEqual(p1, p2))
}
output:
true
func BenchmarkGob(b *testing.B) {
p1 := NewPlayer()
p2 := new(Player)
for i:=0 ; i<b.N ; i++ {
GobDeepCopy(p2, p1)
}
}
goos: windows
goarch: amd64
pkg: game.lab/ go -deepcopy/src/gob
30000 57666 ns/op
PASS
|
标签:return,Level,int,gob,func,go,拷贝,Id 来源: https://www.cnblogs.com/ExMan/p/14292035.html