golang标准库中的encoding/gob包

简介: golang标准库gob编码

1、golang中的gob包是什么?
2、go标准库中的gob编码规则
3、gob包给开发者提供了什么内容?以及怎么使用?
4、gob的目的是什么?以及应用场景有哪些?

一、golang中的gob包是什么?
gob是golang包自带的一个数据结构序列化的编码/解码工具。

二、go标准库中的gob编码规则
image
当发生方传递的是struct{A,B int}结构的值,接收方可以允许前9种结构,但是后4四种结构却是不允许的。

允许模拟相似,但是不允许矛盾

各个类型的编码规则
1、结构体内只有导出字段并且导出字段才能被编码和解码
2、编码至少存在一个可编码字段,解码也至少需要一个能被解码字段,不然会报错。
3、解码方的导出字段必须存在与编码后的同名字段,类型一致,或者接收方为同类型指针,或为指向指针的指针类型。(比如,编码:A int,则解码可以为A int,A int,A int,这三种的一种,虽然A int不会报错,但是接收不到值),如果导出字段名称一样,但是类型不一样(排除前面的那些情况)的话,就会报错。

三、gob包给开发者提供了什么内容?怎么使用?
结构体

type GobDecoder interface
type GobEncoder interface
type Decoder struct
type Encoder struct

函数列表

func Register(value interface{})
func RegisterName(name string, value interface{})
func NewDecoder(r io.Reader) *Decoder
func (dec *Decoder) Decode(e interface{}) error
func (dec *Decoder) DecoderValue(v reflect.Value) error
func NewEncoder(w io.Writer) *Encoder
func (enc *Encoder) Encode(e interface{}) error
func (enc *Encoder) EncodeValue(value reflect.Value) error

详解
1)GobDecoder

type GobDecoder interface {
        GobEecode([]byte) error
}

GobDecoder是一个描述数据的接口,提供自己的方案来解码GobEncoder发送的数据。

2)GobEncoder

type GobEncoder interface {
        GobEncode() ([]byte, error)
}

GobEncoder是一个描述数据的接口,提供自己的方案来将数据编码提供GobDecoder接收并解码。一个实现了GobEncoder接口和GobDecoder接口的类型可以完全控制自身数据的表示,因此可以包含非导出字段、通道、函数等数据,这些数据gob流正常是不能传输的。

// A Decoder manages the receipt of type and data information read from the
// remote side of a connection.
type Decoder struct {
    mutex        sync.Mutex                              // each item must be received atomically
    r            io.Reader                               // source of the data
    buf          bytes.Buffer                            // buffer for more efficient i/o from r
    wireType     map[typeId]*wireType                    // map from remote ID to local description
    decoderCache map[reflect.Type]map[typeId]**decEngine // cache of compiled engines
    ignorerCache map[typeId]**decEngine                  // ditto for ignored objects
    freeList     *decoderState                           // list of free decoderStates; avoids reallocation
    countBuf     []byte                                  // used for decoding integers while parsing messages
    tmp          []byte                                  // temporary storage for i/o; saves reallocating
    err          error
}


// An Encoder manages the transmission of type and data information to the
// other side of a connection.
type Encoder struct {
    mutex      sync.Mutex              // each item must be sent atomically
    w          []io.Writer             // where to send the data
    sent       map[reflect.Type]typeId // which types we've already sent
    countState *encoderState           // stage for writing counts
    freeList   *encoderState           // list of free encoderStates; avoids reallocation
    byteBuf    bytes.Buffer            // buffer for top-level encoderState
    err        error
}

1)func Register(value interface{})
Register记录value下层具体值得类型和其名称。该名称将用来识别发送或接收接口类型值下层的具体类型。本函数只应在初始化调用,如果类型和名字的映射不是一一对应的,会panic。

2)func RegisterName(name string, value interface{})
RegisterName,使用自定义的名称替代类型的默认名称。

3)func NewDecoder(r io.Reader) *Decoder

参数列表:r  Reader对象
返回值:*Decoder  指向Decoder的指针
功能说明:这个函数主要是给r创建一个decoder实例

4)func (des *Decoder) Decode(e interface{}) error

参数列表:e  空接口类型,可以处理任何类型的数据
返回值:error
功能说明:此函数是Decoder的方法即(method),需要使用NewDcoder()创建*Decoder对象后,才可以使用

5)func (dec *Decoder) DecodeValue(v refletc.Value) error

6)func NewEncoder(w io.Writer) *Encoder

7)func (enc *Encoder) Encode(e interface{}) error

参数列表:v  序列化gob对象
返回值:error错误
功能说明:这个函数主要是讲encode编码的gob数据写入到相关联的对象

8)func (enc *Encoder) EncodeValue(value reflect.Value) error
gob自定义内容:

gob的包主要分两块内容,一是自定义gob规则,二是基于go标准库中已实现的gob进行编解码操作。

demo1:自定义gob规则
1)实现GobDecoder、GobEncoder这两个接口
2)编写代码
因为我现在没有重写gob的参考需求,所以就找了一篇讲解重新gob的博客,链接
demo2:使用go标准库已定义好的gob规则

package main

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

type gobSend struct {
    A int
    B float64
}

type gobGet struct {
    A int
    D float64
}

func init() {
    gob.Register(&gobSend{})
    gob.Register(&gobGet{})
}

func main() {
    fmt.Println(gobEncode("1.gob"))
    fmt.Println(gobDecode("1.gob"))
}

func gobEncode(fileName string) error {
    fi, err := os.Create(fileName)
    if err != nil {
        return err
    }
    defer fi.Close()

    encoder := gob.NewEncoder(fi)
    return encoder.Encode(gobSend{1,12})
}

func gobDecode(fileName string) (error) {
    fi, err := os.Open(fileName)
    if err != nil {
        return err
    }
    defer fi.Close()

    decoder := gob.NewDecoder(fi)
    g := gobGet{}
    err = decoder.Decode(&g)
    fmt.Println(g)
    return err
}

四、gob的目的是什么?应用场景?
让数据结构能够在网络上传输或能够保存到文件中。gob可以通过json或gob来序列化struct对象,虽然json的序列化更为通用,但利用gob编码可以实现json所不能支持的struct方法序列化。但是gob是golang提供的“私有”的编码方式,go服务之间通信可以使用gob传输。
一种典型的应用场景就是RPC。程序之间相互通信的。

五、参考链接
1、http://www.cnblogs.com/yjf512/archive/2012/08/24/2653697.html
2、https://studygolang.com/pkgdoc
3、https://blog.csdn.net/sydnash/article/details/61200427

目录
相关文章
|
5月前
|
监控 网络协议 Go
Golang抓包:实现网络数据包捕获与分析
Golang抓包:实现网络数据包捕获与分析
|
6月前
|
负载均衡 中间件 Go
Golang 微服务工具包 Go kit
Golang 微服务工具包 Go kit
43 0
|
6月前
|
存储 Go
Golang 语言标准库 sync/atomic 包原子操作
Golang 语言标准库 sync/atomic 包原子操作
24 0
|
6月前
|
编解码 JSON 网络协议
Golang 语言使用标准库 net/rpc/jsonrpc 包跨语言远程调用
Golang 语言使用标准库 net/rpc/jsonrpc 包跨语言远程调用
62 0
|
6月前
|
Unix Go
Golang 语言的标准库 os 包怎么操作目录和文件?
Golang 语言的标准库 os 包怎么操作目录和文件?
26 0
|
6月前
|
Go
Golang 语言怎么使用 net/http 标准库开发 http 应用?
Golang 语言怎么使用 net/http 标准库开发 http 应用?
26 0
|
6月前
|
Go 芯片 iOS开发
Golang 1.16 新增 embed 包怎么使用?
Golang 1.16 新增 embed 包怎么使用?
57 0
|
6月前
|
存储 Go 索引
Golang 语言标准库 bytes 包怎么使用?
Golang 语言标准库 bytes 包怎么使用?
30 0
|
3月前
|
Go
Golang内置Log包的基本使用
Golang内置Log包的基本使用
25 0
|
4月前
|
JSON Cloud Native 网络协议
golang validator 包的使用指北
golang validator 包的使用指北