Go 中的结构体和 JSON 序列化

高手,打扰一下,Go 中的结构体和 JSON 序列化
最新回答
醉酒吟春秋

2025-03-02 00:09:45

结构体在 Go 语言中是一种将多个变量组合成单一数据类型的方法,类似于 Java 中的 class。在结构体内,可以嵌套其他结构体,甚至定义方法。以下将逐步介绍结构体的定义、使用、带标签的结构体、方法,以及函数与方法的区别。



定义结构体时,我们首先需要定义结构体的名称、字段及其类型。例如:



go
type Point struct {
X int
Y int
}



结构体使用时,可以通过以下三种方式:





  • 使用结构体类型变量直接初始化:





go
p := Point{X: 10, Y: 20}





  • 通过结构体的指针进行初始化:





go
p := &Point{X: 10, Y: 20}





  • 使用工厂模式构造结构体:





go
func NewPoint(x, y int) *Point {
return &Point{X: x, Y: y}
}



带标签的结构体允许我们在字段上附加额外的描述,这些标签在编程时不能直接使用,但可通过反射获取。例如:



go
type Config struct {
Name string `json:"name"`
Value int `json:"value"`
}



在处理 JSON 数据时,标签能帮助我们正确解析和序列化 JSON 对象。例如:



go
data := `{"name": "John", "value": 42}`
config := &Config{}
json.Unmarshal([]byte(data), config)
fmt.Println(config.Name, config.Value)



自定义类型可以拥有方法,除了指针和 interface 外的任何类型皆可。例如:



go
type Str struct {
Value string
}

func (s Str) Compact1(x, y string) string {
return fmt.Sprintf("%s %s", x, y)
}

func (s Str) Compact2() string {
return s.Value
}



在使用方法时,需要注意 Go 中的方法访问控制规范。首字母大写表示公共方法,小写表示私有方法。方法的调用与 Java 中的 this 关键字类似。接收者类型决定了方法的可操作性,例如:



go
type MainConfig1 struct {
Address string
}

func (mc *MainConfig1) Compact2() string {
return mc.Address
}

func (mc *MainConfig1) Compact1(x string) string {
return mc.Address + x
}

func main() {
mf := MainConfig1{Address: "test"}
fmt.Println(mf.Compact1("123"))
}



函数与方法之间的主要区别在于函数接收参数,而方法在接收者的对象上调用。方法可以改变接收者的值(或状态),而函数不能。在使用指针作为接收者时,方法能够修改接收者的值。例如:



go
func (p *Point) SetX(x int) {
p.X = x
}

func main() {
p := Point{X: 1, Y: 1}
p.SetX(2)
fmt.Println(p.X) // 输出 2
}



通过以上介绍,可以更全面地理解 Go 语言中结构体、方法以及函数与方法的区别,进一步掌握 Go 语言的高级特性。