What does gob encoding do?

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

What does gob encoding do?

问题

gob编码/解码有什么作用吗?在下面的示例中,解码之前和解码之后的数据看起来是一样的。我感到困惑,请给予指导。

data := "ABC"
buf := new(bytes.Buffer)

// gob编码
enc := gob.NewEncoder(buf)
enc.Encode(data)
fmt.Println("编码后:", data)  // 编码后: ABC

// gob解码
d := gob.NewDecoder(buf)
d.Decode(data)
fmt.Println("解码后:", data) // 解码后: ABC
英文:

Does gob encoding/decoding do anything ? In the example below , data looks the same before and after decoding. I am confused, please advise

data = "ABC"
	buf := new(bytes.Buffer)
	
	//glob encoding
	enc := gob.NewEncoder(buf)
	enc.Encode(data)
	fmt.Println("Encoded:", data)  //Encoded: ABC
	
	//glob decoding
	d := gob.NewDecoder(buf)
	d.Decode(data)
	fmt.Println("Decoded: ", data) //Decoded:  ABC

答案1

得分: 4

你的比较是错误的 - 将编码前的数据(data)与解码后的结果(d.Decode(data))进行比较,显然会得到相同的结果(如果一切正常的话)。

编码本身将以下划线字节缓冲区的形式呈现(尝试打印缓冲区本身 - fmt.Println(buf.Bytes()))。

gob包上阅读更多信息。

英文:

Your comparison is wrong - comparing the data being encoded (data) to the result after being decoded (d.Decode(data)), will obviously lead you to the same result (if everything is working as expected).

The encoding itself will be presented in the underline bytes buffer (try to print the buffer itself - fmt.Println(buf.Bytes())).

Read more on the gob package

huangapple
  • 本文由 发表于 2017年3月5日 03:33:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/42600441.html
匿名

发表评论

匿名网友

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

确定