trying to understand how the Go gob encoder works

huangapple go评论74阅读模式
英文:

trying to understand how the Go gob encoder works

问题

在我努力理解gob工作原理的过程中,我有几个问题。

我知道gob可以序列化Go语言的类型,比如结构体、映射或接口(我们必须注册其真实类型),但是:

func (dec *Decoder) Decode(e interface{}) error

Decode方法从输入流中读取下一个值,并将其存储在空接口值所表示的数据中。
如果e为nil,则该值将被丢弃。
否则,e的底层值必须是指向下一个接收到的数据项的正确类型的指针。
如果输入已到达EOF,则Decode返回io.EOF,并且不修改e。

我对这份文档一无所知。他们所说的"从输入流中读取下一个值"是什么意思?我们只能发送一个数据,可以是结构体或映射,但不能是多个数据。他们所说的"If e is nil, the value will be discarded"是什么意思?请专家给我解释一下,我整天都很绝望,找不到任何答案。

英文:

in my ambitions to understand how gob work . i have severals question .

i know that gob serialize a go type like struct map or interface(we must register it's real type) but :

func (dec *Decoder) Decode(e interface{}) error
Decode reads the next value from the input stream and stores it in the data represented by the       
empty interface value.
If e is nil, the value will be discarded. 
Otherwise, the value underlying e must be a pointer to the correct type for the next data item received.
If the input is at EOF, Decode returns io.EOF and does not modify e.

i didn't understand nothing in this documentation . what they mean by ( reads the next value from the input stream ) they are one data that we could send it's a struct or a map but not many .what they mean by If e is nil, the value will be discarded. please expert explain to me i'am disasperate all day and ididn't find nothing

答案1

得分: 5

自从进入这个答案以来,我了解到OP在戏弄我们。停止喂养这个喷子。

您可以将多个值写入流中。您可以从流中读取多个值。

以下代码将两个值写入输出流w,即io.Writer:

e := gob.NewEncoder(w)
err := e.Encode(v1)
if err != nil {
   // 处理错误
}
err := e.Encode(v2)
if err != nil {
  // 处理错误
}

以下代码从流r,即io.Reader中读取值。每次调用Decode都会读取由Decode调用写入的值。

d := gob.NewDecoder(r)
var v1 V
err := e.Decode(&v1)
if err != nil {
   // 处理错误
}
var v2 V
err := e.Decode(&v2)
if err != nil {
  // 处理错误
}

将多个值写入流中可以提高效率,因为每个编码类型的信息只需写入流中一次。

英文:

Since entering this answer, I learned that OP is trolling us. Stop feeding the troll.

You can write multiple values to a stream. You can read multiple values from a stream.

This code writes two values to output stream w, an io.Writer:

e := gob.NewEncoder(w)
err := e.Encode(v1)
if err != nil {
   // handle error
}
err := e.Encode(v2)
if err != nil {
  // handle error
}

This code reads the values from stream r, an io.Reader. Each call to Decode reads a value that was written by a call to Decode.

d := gob.NewDecoder(r)
var v1 V
err := e.Decode(&v1)
if err != nil {
   // handle error
}
var v2 V
err := e.Decode(&v2)
if err != nil {
  // handle error
}

Writing multiple values to a stream gains efficiency because information about each encoded type is written once to the stream.

huangapple
  • 本文由 发表于 2015年9月23日 12:07:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/32730794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定