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
请发表评论