← 中文资源

简体中文版本

Gob 往返序列化复合值

encoding/gob 把带 map 与 slice 的结构体编码成自描述字节流再解码到全新值:复合字段深度还原,改解码值不影响原始数据。

阅读英文原文

实现说明

Gob 往返序列化复合值以函数 main为骨架。 失败处理就是 panic(err):2 个检查点在问题出现的地方中止程序。

使用要点

  • panic(err) 是这里唯一的失败路径:第一个问题就会终止程序。
  • 演示输出是带标签的(encoded bytes:、original intact:),每个操作都会留下自己的一行标注。

常见问题

调用方该如何处理失败?

以终止运行上报:2 处检查都会触发 panic(err),调用方看到的失败就是程序停下。

运行「Gob 往返序列化复合值」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 encoded bytes:、original intact: 标签标明各步骤。

代码示例

package main

import (
	"bytes"
	"encoding/gob"
	"fmt"
)

type Snapshot struct {
	Name   string
	Scores map[string]int
	Tags   []string
}

func main() {
	sent := Snapshot{
		Name:   "stage-1",
		Scores: map[string]int{"lint": 98, "unit": 87},
		Tags:   []string{"ci", "nightly"},
	}

	// gob encodes into the buffer: composite values like maps and slices serialize too
	var wire bytes.Buffer
	if err := gob.NewEncoder(&wire).Encode(sent); err != nil {
		panic(err)
	}
	fmt.Println("encoded bytes:", wire.Len())

	// Decode into fresh values: field types are restored from gob's self-describing stream
	var got Snapshot
	if err := gob.NewDecoder(&wire).Decode(&got); err != nil {
		panic(err)
	}
	fmt.Println(got.Name, got.Scores["unit"], got.Tags)

	// Map and slice are deeply reconstructed: mutating the decoded value leaves the original untouched
	got.Scores["lint"] = 0
	fmt.Println("original intact:", sent.Scores["lint"])
}