首页 > IT职业 > IT图书 > 【golang】浅析类属性大小写区别
我们知道Golang里都是通过结构体Struct来定义类和相关属性的。这里有点需要注意的是,属性的首字母大小写表示的意义是不同的!
go中根据首字母的大小写来确定可以访问的权限。无论是方法名、常量、变量名还是结构体的名称,如果首字母大写,则可以被其他的包访问;如果首字母小写,则只能在本包中使用。
可以简单的理解成,首字母大写是公有的,首字母小写是私有的
但是这些都不是重点,毕竟这些很多人都知道。
还有一个很大的不同时超哥在写项目中遇到的(惭愧啊,go基础还是不扎实):
package mainimport ( "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无法解析
}
}
运行结果:

image.png
.
.
.
.
互联网颠覆世界,区块链颠覆互联网!
作者:chaors
链接:https://www.jianshu.com/p/bbcdb79ca869
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2763/viewspace-2804992/ ,如需转载,请注明出处,否则将追究法律责任。