前言
结构是多种类型的集合,它本身就是类型的一种,因此需要用type
关键字来声明
鉴于上述的性质,常用来描述一个具有多种属性的类。
例如,人类,书本等。
写法和使用
当定义好一个struct后,就可以通过var声明struct类型了
package main
import "fmt"
type Person struct {
name string
age int
}
type Book struct {
title string
author string
}
func readBook(b *Book) {
fmt.Printf("他们读取的书籍:%s\n", (*b).title)
}
func main(){
p1 := Person{"zhangsan", 20}
p2 := Person{name:"lisi", age:10}
b := Book{title:"魔兽世界", author:"wangwu"}
fmt.Println(p1.name, p2.name)
readBook(&b)
}
zhangsan lisi
他们读取的书籍:魔兽世界
结构和数据格式之间的编解码
定义结构的时候,添加数据格式映射关系
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
ID int
FirstName string `json:"name"`
LastName string
Address string `json:"address,omitempty"`
}
type Employee struct {
Person
ManagerID int
}
type Contractor struct {
Person
CompanyID int
}
func main() {
employees := []Employee{
Employee{
Person: Person{
LastName: "Doe", FirstName: "John",
},
},
Employee{
Person: Person{
LastName: "Campbell", FirstName: "David",
},
},
}
data, _ := json.Marshal(employees)
fmt.Printf("%s\n", data)
var decoded []Employee
json.Unmarshal(data, &decoded)
fmt.Printf("%v", decoded)
}
[{"ID":0,"name":"John","LastName":"Doe","ManagerID":0},{"ID":0,"name":"David","LastName":"Campbell","ManagerID":0}]
[{{0 John Doe } 0} {{0 David Campbell } 0}]
在上面的代码中,有一段若改为下面代码,则报错
Employee{
Person: Person{
LastName: "Doe", FirstName: "John", "Beijing"
},
},
因为不可将初始化值方式和直接赋值方式混用。正确的写法如下:
Employee{
Person: Person{
LastName: "Doe", FirstName: "John", Address: "Beijing"
},
},
✨结构对象中没有初始化的属性,则会自动附加默认值。