分享
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。


package main
import (
"bytes"
"encoding/gob"
"log"
)
func main() {
//知识背景 序列化
//golang可以通过json或gob来序列化struct对象,虽然json的序列化更为通用,但利用gob编码可以实现json所不能支持的struct的方法序列化,利用gob包序列化struct保存到本地也十分简单
//gob和json的pack之类的方法一样,由发送端使用Encoder对数据结构进行编码。在接收端收到消息之后,接收端使用Decoder将序列化的数据变化成本地变量。
//rpc remote 场景
var str string = "xiaochuan"
e, err := Encode(str)
if err != nil {
log.Println(err.Error())
}
log.Println(string(e)) //强制转换
//new
//官方文档
// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
//func new(Type) *Type
info_new := new(string)
err1 := Decode(e, info_new)
if err1 != nil {
log.Println(err1.Error())
}
log.Println(*info_new)
}
// 用gob进行数据编码
func Encode(data interface{}) ([]byte, error) {
buf := bytes.NewBuffer(nil)
enc := gob.NewEncoder(buf)
err := enc.Encode(data)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// 用gob进行数据解码
func Decode(data []byte, to interface{}) error { //inteface 万能型的class , 非常开心,兴趣是最大的动力
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
return dec.Decode(to)
}
运行结果

END.
有疑问加站长微信联系(非本文作者))
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信3175 次点击
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传