Go 數(shù)據(jù)存儲篇(四):通過 Gob 包序列化二進(jìn)制數(shù)據(jù)

前面兩篇教程學(xué)院君給大家介紹了如何基于 JSON 和 CSV 格式序列化數(shù)據(jù)到文本文件,除此之外,Go 官方還提供了 encoding/gob 包將數(shù)據(jù)序列化為二進(jìn)制流以便通過網(wǎng)絡(luò)進(jìn)行傳輸。
我們在前面 Go 入門教程中已經(jīng)介紹過 Gob 包作為二進(jìn)制數(shù)據(jù)編解碼工具的基本使用,這里簡單演示下如何將 Gob 編碼后的二進(jìn)制數(shù)據(jù)寫入磁盤文件:
package?main
import?(
????"bytes"
????"encoding/gob"
????"fmt"
????"io/ioutil"
)
type?Article?struct?{
????Id?int
????Title?string
????Content?string
????Author?string
}
//?寫入二進(jìn)制數(shù)據(jù)到磁盤文件
func?write(data?interface{},?filename?string)??{
????buffer?:=?new(bytes.Buffer)
????encoder?:=?gob.NewEncoder(buffer)
????err?:=?encoder.Encode(data)
????if?err?!=?nil?{
????????panic(err)
????}
????err?=?ioutil.WriteFile(filename,?buffer.Bytes(),?0600)
????if?err?!=?nil?{
????????panic(err)
????}
}
//?從磁盤文件加載二進(jìn)制數(shù)據(jù)
func?read(data?interface{},?filename?string)?{
????raw,?err?:=?ioutil.ReadFile(filename)
????if?err?!=?nil?{
????????panic(err)
????}
????buffer?:=?bytes.NewBuffer(raw)
????dec?:=?gob.NewDecoder(buffer)
????err?=?dec.Decode(data)
????if?err?!=?nil?{
????????panic(err)
????}
}
func?main()??{
????article?:=?Article{
????????Id:?1,
????????Title:?"基于?Gob?包編解碼二進(jìn)制數(shù)據(jù)",
????????Content:?"通過?Gob?包序列化二進(jìn)制數(shù)據(jù)以便通過網(wǎng)絡(luò)傳輸",
????????Author:?"學(xué)院君",
????}
????write(article,?"article_data")
????var?articleData?Article
????read(&articleData,?"article_data")
????fmt.Printf("%#v\n",?articleData)
}
運(yùn)行上述代碼,可以正常解碼出二進(jìn)制數(shù)據(jù),說明通過 Gob 包編解碼成功:

在當(dāng)前目錄下也可以看到生成的 article_data 文件,其中包含的是二進(jìn)制格式的編碼數(shù)據(jù):

關(guān)于文本數(shù)據(jù)和二進(jìn)制數(shù)據(jù)的序列化我們就簡單介紹到這里,下篇教程開始,學(xué)院君將開始給大家介紹如何在 Go 語言中通過數(shù)據(jù)庫存取數(shù)據(jù)。
(全文完)
推薦閱讀

評論
圖片
表情
