【golang】序列化例子浅析类属性大小写区别

我们知道Golang里都是通过结构体Struct来定义类和相关属性的。这里有点需要注意的是,属性的首字母大小写表示的意义是不同的!

go中根据首字母的大小写来确定可以访问的权限。无论是方法名、常量、变量名还是结构体的名称,如果首字母大写,则可以被其他的包访问;如果首字母小写,则只能在本包中使用。

可以简单的理解成,首字母大写是公有的,首字母小写是私有的

但是这些都不是重点,毕竟这些很多人都知道。

还有一个很大的不同时超哥在写项目中遇到的(惭愧啊,go基础还是不扎实):

类属性如果是小写开头,则其序列化会丢失属性对应的值,同时也无法进行Json解析

废话少说上代码

package main

import (
	"bytes"
	"encoding/gob"
	"encoding/json"
	"fmt"
	"log"
)
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无法解析
	}

}

 结果:

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值