我們知道Golang里都是通過結(jié)構(gòu)體Struct來定義類和相關(guān)屬性的。這里有點需要注意的是谴古,屬性的首字母大小寫表示的意義是不同的撞羽!
go中根據(jù)首字母的大小寫來確定可以訪問的權(quán)限。無論是方法名、常量煤杀、變量名還是結(jié)構(gòu)體的名稱眷蜈,如果首字母大寫,則可以被其他的包訪問沈自;如果首字母小寫酌儒,則只能在本包中使用。
可以簡單的理解成枯途,首字母大寫是公有的忌怎,首字母小寫是私有的
但是這些都不是重點,畢竟這些很多人都知道酪夷。
還有一個很大的不同時超哥在寫項目中遇到的(慚愧啊榴啸,go基礎(chǔ)還是不扎實):
類屬性如果是小寫開頭,則其序列化會丟失屬性對應(yīng)的值晚岭,同時也無法進(jìn)行Json解析鸥印。
廢話少說上代碼
package main
import (
"bytes"
"encoding/gob"
"log"
"encoding/json"
"fmt"
)
type People struct {
Name string
Age int
description string //注意這個屬性和上面不同,首字母小寫
}
//序列化
func (people *People) Serialize() []byte {
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
err := encoder.Encode(people)
if err != nil{
log.Panic(err)
}
return result.Bytes()
}
//反序列化
func DeSerializeBlock(peopleBytes []byte) *People {
var people People
decoder := gob.NewDecoder(bytes.NewReader(peopleBytes))
err := decoder.Decode(&people)
if err != nil {
log.Panic(err)
}
return &people
}
func main () {
people := People{
"chaors",
27,
"a good good boy",
}
fmt.Println()
fmt.Println("序列化前:", people)
//序列化
peopleBytes := people.Serialize()
//反序列化取出
fmt.Println()
fmt.Println("反序列化取出:", DeSerializeBlock(peopleBytes))
fmt.Println()
//Json解析
if peopleJson, err := json.Marshal(people); err == nil {
fmt.Println("Json解析:", string(peopleJson)) //description無法解析
}
}
運(yùn)行結(jié)果:
image.png
更多原創(chuàng)區(qū)塊鏈技術(shù)文章請訪問chaors
.
.
.
.
互聯(lián)網(wǎng)顛覆世界坦报,區(qū)塊鏈顛覆互聯(lián)網(wǎng)!
--------------------------------------------------20180703 20:30