package gob
import "encoding/gob"
Package gob 管理 gob 流——在 Encoder(发送方)与 Decoder(接收方)之间交换的 二进制值。一种典型用途是传输远程过程调用(RPC,例如 net/rpc 所提供的那些) 的参数和结果。
该实现会为流中的每种数据类型编译一个定制的编解码器,并且当使用单个 Encoder 来传输一个值流时效率最高,因为这样可以摊薄编译成本。
基础
gob 流是自描述的。流中的每个数据项前面都带有其类型的说明,该说明以一小 组预定义类型来表示。指针不会被传输,但它们所指向的内容会被传输;也就是 说,值会被展平。nil 指针不被允许,因为它们没有值。递归类型工作良好,但 递归值(带环的数据)则存在问题。这一点可能会改变。
要使用 gob,请创建一个 Encoder,并向它依次提供一系列数据项,这些数据 项可以是值,也可以是可解引用为值的地址。Encoder 会确保所有类型信息在 需要之前就已发送。在接收端,Decoder 从编码后的流中取回值,并将它们解包 到局部变量中。
类型与值
源和目标的值/类型不必完全对应。对于结构体,源中存在但接收变量中不存在的 字段(按名称识别)将被忽略。接收变量中存在但传输的类型或值中缺失的字段, 在目标中将被忽略。如果两边都存在同名字段,它们的类型必须兼容。接收方和发送 方都会执行所有必要的间接寻址和解引用,以便在 gob 与实际的 Go 值之间进行 转换。例如,一个示意上为
struct { A, B int }
的 gob 类型,可以从以下任一 Go 类型发送或接收进:
struct { A, B int } // the same
*struct { A, B int } // extra indirection of the struct
struct { *A, **B int } // extra indirection of the fields
struct { A, B int64 } // different concrete value type; see below
它也可以被接收进以下任一类型:
struct { A, B int } // the same
struct { B, A int } // ordering doesn't matter; matching is by name
struct { A, B, C int } // extra field (C) ignored
struct { B int } // missing field (A) ignored; data will be dropped
struct { B, C int } // missing field (A) ignored; extra field (C) ignored.
尝试接收进以下类型将引发解码错误:
struct { A int; B uint } // change of signedness for B
struct { A int; B float } // change of type for B
struct { } // no field names in common
struct { C, D int } // no field names in common
整数以两种方式传输:任意精度的有符号整数,或任意精度的无符号整数。gob 格式 中不区分 int8、int16 等;只有有符号整数和无符号整数。如下文所述,发送方以 变长编码发送值;接收方接受该值并将其存入目标变量。浮点数始终使用 IEEE 754 64 位精度发送(见下文)。
有符号整数可以被接收进任何有符号整数变量:int、int16 等;无符号整数可以被 接收进任何无符号整数变量;浮点值可以被接收进任何浮点变量。不过,目标变量 必须能够表示该值,否则解码操作将失败。
结构体、数组和切片也受支持。结构体只编码和解码已导出字段。字符串和字节数组 以一种特殊的、高效的表示形式受支持(见下文)。解码切片时,如果现有切片具有 容量,则该切片会被原地扩展;如果没有,则分配一个新数组。无论如何,结果切片 的长度都会报告已解码的元素个数。
一般而言,如果需要分配,解码器将分配内存。如果不需要,它会用从流中读取的值 更新目标变量。它不会先初始化这些变量,因此如果目标是 map、结构体或切片这类 复合值,解码得到的值将按元素合并进现有变量中。
函数和通道不会被发送到 gob 中。尝试在顶层编码这样的值将失败。chan 或 func 类型的结构体字段会被完全当作未导出字段处理,并被忽略。
Gob 可以通过调用相应方法,对任何实现了 GobEncoder 或 encoding.BinaryMarshaler 接口的值进行编码,按上述优先级顺序。
Gob 可以通过调用相应方法,对任何实现了 GobDecoder 或 encoding.BinaryUnmarshaler 接口的值进行解码,同样按上述优先级顺序。
编码细节
本节记录编码细节,这些细节对大多数用户并不重要。细节按自底向上的顺序呈现。
无符号整数以两种方式之一发送。如果它小于 128,就作为带有该值的一个字节发送。 否则,就作为以最小长度的大端序(高字节在前)字节流保存该值来发送,其前面是 一个保存字节数取负后的字节。因此 0 被传输为 (00),7 被传输为 (07),256 被 传输为 (FE 01 00)。
布尔值编码在一个无符号整数之内:0 表示 false,1 表示 true。
有符号整数 i 编码在一个无符号整数 u 之内。在 u 中,从第 1 位起往上保存该值; 第 0 位表示在接收时它们是否应当被取反。编码算法如下:
var u uint
if i < 0 {
u = (^uint(i) << 1) | 1 // complement i, bit 0 is 1
} else {
u = (uint(i) << 1) // do not complement i, bit 0 is 0
}
encodeUnsigned(u)
因此,低位类似于符号位,但把它改为取反位则保证了最大的负整数不是特例。例如, -129=^128=(^256>>1) 编码为 (FE 01 01)。
浮点数始终以 float64 值的表示形式发送。该值使用 math.Float64bits 转换为 uint64。然后该 uint64 被字节反转,并作为常规无符号整数发送。字节反转意味着 指数和尾数的高精度部分先出现。由于低位常常为零,这可以节省编码字节。例如, 17.0 只编码为三个字节 (FE 31 40)。
字符串和字节切片作为无符号计数后跟该数量的未经解释的值字节发送。
所有其他切片和数组都作为无符号计数后跟该数量的元素发送,元素使用其类型的 标准 gob 编码递归地进行编码。
Map 作为无符号计数后跟该数量的键、元素对发送。空的但非 nil 的 map 也会被 发送,因此如果接收方尚未分配一个 map,那么在接收时总会分配一个,除非所 传输的 map 为 nil 且不在顶层。
在切片和数组中,以及在 map 中,所有元素——即使是零值元素——都会被传输,即使 所有元素都为零。
结构体作为一系列(字段号,字段值)对发送。字段值使用其类型的标准 gob 编码 递归地发送。如果某个字段具有其类型的零值(数组除外;见上文),或者它是指向 零值的指针,则会从传输中省略。字段号由被编码结构体的类型定义:被编码类型的 第一个字段是字段 0,第二个是字段 1,依此类推。编码某个值时,字段号为效率而 采用增量编码,且字段总是按字段号递增的顺序发送;因此增量是无符号的。增量 编码的初始化将字段号设为 -1,因此一个值为 7 的无符号整数字段 0 被传输为 无符号增量 = 1、无符号值 = 7,即 (01 07)。最后,在所有字段都发送完之后,一个 终止标记表示结构体的结束。该标记是一个 delta=0 的值,其表示为 (00)。
接口类型不进行兼容性检查;在传输时,所有接口类型都被当作单一 "interface" 类型的成员处理,类似于 int 或 []byte ——实际上它们都被当作 interface{}。 接口值作为这样一个字符串发送:它标识正在发送的具体类型(该名称必须通过调用 Register 预先定义),后跟随后数据长度的字节计数(以便在无法存储该值时 跳过它),再后跟存储在接口值中的具体(动态)值的常规编码。(nil 接口值由空 字符串标识,且不传输任何值。)接收时,解码器验证解包出的具体项是否满足接收 变量的接口。
如果某个值被传给 Encoder.Encode,且其类型不是结构体(或指向结构体的指针等), 为简化处理,它会被表示为一个含单个字段的结构体。唯一可见的效果是在该值之后 编码一个零字节,就像在编码后的结构体的最后一个字段之后那样,以便解码算法 知道顶层值何时结束。
类型的表示如下所述。当某个类型在 Encoder 与 Decoder 之间的给定连接上被 定义时,它会被分配一个有符号整数类型 id。当调用 Encoder.Encode(v) 时,它 会确保为 v 的类型及其所有元素都分配了 id,然后发送对 (typeid, encoded-v), 其中 typeid 是 v 被编码类型的类型 id,encoded-v 是值 v 的 gob 编码。
要定义类型,编码器选择一个未使用的正类型 id,并发送对 (-type id, encoded-type), 其中 encoded-type 是 wireType 描述的 gob 编码,由以下类型构造而来:
type wireType struct {
ArrayT *arrayType
SliceT *sliceType
StructT *structType
MapT *mapType
GobEncoderT *gobEncoderType
BinaryMarshalerT *gobEncoderType
TextMarshalerT *gobEncoderType
}
type arrayType struct {
CommonType
Elem typeId
Len int
}
type CommonType struct {
Name string // the name of the struct type
Id int // the id of the type, repeated so it's inside the type
}
type sliceType struct {
CommonType
Elem typeId
}
type structType struct {
CommonType
Field []fieldType // the fields of the struct.
}
type fieldType struct {
Name string // the name of the field.
Id int // the type id of the field, which must be already defined
}
type mapType struct {
CommonType
Key typeId
Elem typeId
}
type gobEncoderType struct {
CommonType
}
如果存在嵌套的类型 id,那么所有内部类型 id 的类型必须在顶层类型 id 被用于 描述 encoded-v 之前定义好。
为简化设置,连接被定义为先验地理解这些类型,以及基本的 gob 类型 int、uint 等。它们的 id 为:
bool 1 int 2 uint 3 float 4 []byte 5 string 6 complex 7 interface 8 // 为保留的 id 留出的间隙。 WireType 16 ArrayType 17 CommonType 18 SliceType 19 StructType 20 FieldType 21 // 22 是 fieldType 的切片。 MapType 23
最后,Encode 调用所创建的每条消息前面都带有一个经过编码的无符号整数,表示 消息中剩余字节的数量。在初始类型名之后,接口值也以同样的方式包装;实际上, 接口值就像是对 Encode 的递归调用。
总之,一个 gob 流看起来像
(byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))*
其中 * 表示零次或多次重复,并且某个值的类型 id 必须已预定义,或在流中于该值 之前定义好。
兼容性:本包未来的任何变更都将尽力保持与使用先前版本编码的流的兼容性。也就是 说,本包任何已发布的版本都应能够解码用任何先前已发布版本写入的数据,但受安全 修复之类问题的影响。背景参见 Go 兼容性文档:https://golang.org/doc/go1compat
关于 gob 线格式的设计讨论,参见 "Gobs of data": https://go.dev/blog/gob
安全性
本包并非设计用来抵御对抗性输入,且不在 https://go.dev/security/policy 的
范围内。尤其是,Decoder 对解码所得的输入大小只做基本的健全性检查,且其限制
不可配置。在解码来自不可信来源的 gob 数据时应小心,此类数据可能会消耗大量
资源。
This example shows the basic usage of the package: Create an encoder,
transmit some values, receive them with a decoder.
Output: This example transmits a value that implements the custom encoding and decoding methods.
Output: This example shows how to encode an interface value. The key
distinction from regular types is to register the concrete type that
implements the interface.
Output:Example (Basic)
package main
import (
"bytes"
"encoding/gob"
"fmt"
"log"
)
type P struct {
X, Y, Z int
Name string
}
type Q struct {
X, Y *int32
Name string
}
// This example shows the basic usage of the package: Create an encoder,
// transmit some values, receive them with a decoder.
func main() {
// Initialize the encoder and decoder. Normally enc and dec would be
// bound to network connections and the encoder and decoder would
// run in different processes.
var network bytes.Buffer // Stand-in for a network connection
enc := gob.NewEncoder(&network) // Will write to network.
dec := gob.NewDecoder(&network) // Will read from network.
// Encode (send) some values.
err := enc.Encode(P{3, 4, 5, "Pythagoras"})
if err != nil {
log.Fatal("encode error:", err)
}
err = enc.Encode(P{1782, 1841, 1922, "Treehouse"})
if err != nil {
log.Fatal("encode error:", err)
}
// Decode (receive) and print the values.
var q Q
err = dec.Decode(&q)
if err != nil {
log.Fatal("decode error 1:", err)
}
fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
err = dec.Decode(&q)
if err != nil {
log.Fatal("decode error 2:", err)
}
fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
}
"Pythagoras": {3, 4}
"Treehouse": {1782, 1841}
Example (EncodeDecode)
package main
import (
"bytes"
"encoding/gob"
"fmt"
"log"
)
// The Vector type has unexported fields, which the package cannot access.
// We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us
// to send and receive the type with the gob package. These interfaces are
// defined in the "encoding" package.
// We could equivalently use the locally defined GobEncode/GobDecoder
// interfaces.
type Vector struct {
x, y, z int
}
func (v Vector) MarshalBinary() ([]byte, error) {
// A simple encoding: plain text.
var b bytes.Buffer
fmt.Fprintln(&b, v.x, v.y, v.z)
return b.Bytes(), nil
}
// UnmarshalBinary modifies the receiver so it must take a pointer receiver.
func (v *Vector) UnmarshalBinary(data []byte) error {
// A simple encoding: plain text.
b := bytes.NewBuffer(data)
_, err := fmt.Fscanln(b, &v.x, &v.y, &v.z)
return err
}
// This example transmits a value that implements the custom encoding and decoding methods.
func main() {
var network bytes.Buffer // Stand-in for the network.
// Create an encoder and send a value.
enc := gob.NewEncoder(&network)
err := enc.Encode(Vector{3, 4, 5})
if err != nil {
log.Fatal("encode:", err)
}
// Create a decoder and receive a value.
dec := gob.NewDecoder(&network)
var v Vector
err = dec.Decode(&v)
if err != nil {
log.Fatal("decode:", err)
}
fmt.Println(v)
}
{3 4 5}
Example (Interface)
package main
import (
"bytes"
"encoding/gob"
"fmt"
"log"
"math"
)
type Point struct {
X, Y int
}
func (p Point) Hypotenuse() float64 {
return math.Hypot(float64(p.X), float64(p.Y))
}
type Pythagoras interface {
Hypotenuse() float64
}
// This example shows how to encode an interface value. The key
// distinction from regular types is to register the concrete type that
// implements the interface.
func main() {
var network bytes.Buffer // Stand-in for the network.
// We must register the concrete type for the encoder and decoder (which would
// normally be on a separate machine from the encoder). On each end, this tells the
// engine which concrete type is being sent that implements the interface.
gob.Register(Point{})
// Create an encoder and send some values.
enc := gob.NewEncoder(&network)
for i := 1; i <= 3; i++ {
interfaceEncode(enc, Point{3 * i, 4 * i})
}
// Create a decoder and receive some values.
dec := gob.NewDecoder(&network)
for i := 1; i <= 3; i++ {
result := interfaceDecode(dec)
fmt.Println(result.Hypotenuse())
}
}
// interfaceEncode encodes the interface value into the encoder.
func interfaceEncode(enc *gob.Encoder, p Pythagoras) {
// The encode will fail unless the concrete type has been
// registered. We registered it in the calling function.
// Pass pointer to interface so Encode sees (and hence sends) a value of
// interface type. If we passed p directly it would see the concrete type instead.
// See the blog post, "The Laws of Reflection" for background.
err := enc.Encode(&p)
if err != nil {
log.Fatal("encode:", err)
}
}
// interfaceDecode decodes the next interface value from the stream and returns it.
func interfaceDecode(dec *gob.Decoder) Pythagoras {
// The decode will fail unless the concrete type on the wire has been
// registered. We registered it in the calling function.
var p Pythagoras
err := dec.Decode(&p)
if err != nil {
log.Fatal("decode:", err)
}
return p
}
5
10
15
Index
- func Register(value any)
- func RegisterName(name string, value any)
- type CommonType
- type Decoder
- type Encoder
- type GobDecoder
- type GobEncoder
Examples
Functions
func Register
func Register(value any)
Register 记录一个类型(由该类型的一个值标识),并使用其 内部类型名。该名称将标识作为 interface 变量发送或接收的值的 具体类型。只有将作为 interface 值的实现来传输的类型才需要注册。 预期仅在初始化期间使用;如果类型与名称之间的映射不是双射, 它会 panic。
func RegisterName
func RegisterName(name string, value any)
RegisterName 类似于 Register,但使用提供的名称而非 类型的默认名称。
Types
type CommonType
type CommonType struct { Name string Id typeId }
CommonType 保存所有类型的公共元素。 它是一个历史遗留物,为二进制兼容性而保留,并且仅为本包编码类型描述符 而导出。它不供客户端直接使用。
type Decoder
type Decoder struct { // contains filtered or unexported fields }
Decoder 管理从连接远端读取类型和数据信息的接收过程。 它可以安全地被多个 goroutine 并发使用。
Decoder 对解码所得的输入大小只做基本的健全性检查, 且其限制不可配置。在解码来自不可信来源的 gob 数据时要小心。
func NewDecoder
func NewDecoder(r io.Reader) *Decoder
NewDecoder 返回一个新的解码器,它从 io.Reader 读取。 如果 r 未同时实现 io.ByteReader,它将被包装在一个 bufio.Reader 中。
func (*Decoder) Decode
func (dec *Decoder) Decode(e any) error
Decode 从输入流中读取下一个值,并将其存储到空接口值所表示的数据中。 如果 e 为 nil,则该值将被丢弃。否则,e 底层所表示的值必须是指向 接收到的下一个数据项正确类型的指针。 如果输入已到达 EOF,Decode 返回 io.EOF 且不修改 e。
func (*Decoder) DecodeValue
func (dec *Decoder) DecodeValue(v reflect.Value) error
DecodeValue 从输入流中读取下一个值。 如果 v 是零值 reflect.Value(v.Kind() == Invalid),DecodeValue 会丢弃该值。 否则,它会将值存储到 v 中。在这种情况下,v 必须表示一个指向数据的非 nil 指针, 或者是一个可赋值的 reflect.Value(v.CanSet())。 如果输入已到达 EOF,DecodeValue 返回 io.EOF 且不修改 v。
type Encoder
type Encoder struct { // contains filtered or unexported fields }
Encoder 管理向连接另一端传输类型和数据信息。 它可以安全地被多个 goroutine 并发使用。
func NewEncoder
func NewEncoder(w io.Writer) *Encoder
NewEncoder 返回一个新的编码器,它将在 io.Writer 上传输。
func (*Encoder) Encode
func (enc *Encoder) Encode(e any) error
Encode 传输由空接口值表示的数据项,保证所有必要的类型信息 都已先行传输。向 Encoder 传入 nil 指针会 panic, 因为它们无法由 gob 传输。
func (*Encoder) EncodeValue
func (enc *Encoder) EncodeValue(value reflect.Value) error
EncodeValue 传输由反射值表示的数据项,保证所有必要的类型信息 都已先行传输。向 EncodeValue 传入 nil 指针会 panic, 因为它们无法由 gob 传输。
type GobDecoder
type GobDecoder interface { // GobDecode 用字节切片所表示的值覆盖接收者(接收者必须是指针), // 该字节切片由 GobEncode 写入,通常用于相同的具体类型。 GobDecode([]byte) error }
GobDecoder 是描述数据的接口,这些数据为解码由 GobEncoder 发送的传输值提供自己的例程。
type GobEncoder
type GobEncoder interface { // GobEncode 返回一个字节切片,表示接收者的编码,以便传输给 // GobDecoder,通常用于相同的具体类型。 GobEncode() ([]byte, error) }
GobEncoder 是描述数据的接口,这些数据为编码值以传输给 GobDecoder 提供自己的表示形式。 同时实现 GobEncoder 和 GobDecoder 的类型对其数据的表示形式拥有完全 控制权,因此可以包含诸如私有字段、通道和函数之类的内容, 这些内容通常无法在 gob 流中传输。
注意:由于 gob 可以被永久存储,保证 GobEncoder 所使用的编码随 软件演进保持稳定是一种良好的设计。例如,让 GobEncode 在编码中包含一个版本号可能是有意义的。