go Struct 结构体

go Struct 结构体

结构体是将零个或多个任意类型的变量,组合在一起的聚合数据类型,也可以看做是数据的集合

声明结构体

 1//demo_11.go
 2package main
 3
 4import (
 5	"fmt"
 6)
 7
 8type Person struct {
 9	Name string
10	Age int
11}
12
13func main() {
14	var p1 Person
15	p1.Name = "Tom"
16	p1.Age  = 30
17	fmt.Println("p1 =", p1)
18
19	var p2 = Person{Name:"Burke", Age:31}
20	fmt.Println("p2 =", p2)
21
22	p3 := Person{Name:"Aaron", Age:32}
23	fmt.Println("p2 =", p3)
24
25	//匿名结构体
26	p4 := struct {
27		Name string
28		Age int
29	} {Name:"匿名", Age:33}
30	fmt.Println("p4 =", p4)
31}

生成 JSON

 1//demo_12.go
 2package main
 3
 4import (
 5	"encoding/json"
 6	"fmt"
 7)
 8
 9type Result struct {
10	Code    int    `json:"code"`
11	Message string `json:"msg"`
12}
13
14func main() {
15	var res Result
16	res.Code    = 200
17	res.Message = "success"
18
19	//序列化
20	jsons, errs := json.Marshal(res)
21	if errs != nil {
22		fmt.Println("json marshal error:", errs)
23	}
24	fmt.Println("json data :", string(jsons))
25
26	//反序列化
27	var res2 Result
28	errs = json.Unmarshal(jsons, &res2)
29	if errs != nil {
30		fmt.Println("json unmarshal error:", errs)
31	}
32	fmt.Println("res2 :", res2)
33}

改变数据

 1//demo_13.go
 2package main
 3
 4import (
 5	"encoding/json"
 6	"fmt"
 7)
 8
 9type Result struct {
10	Code    int    `json:"code"`
11	Message string `json:"msg"`
12}
13
14func main() {
15	var res Result
16	res.Code    = 200
17	res.Message = "success"
18	toJson(&res)
19
20	setData(&res)
21	toJson(&res)
22}
23
24func setData (res *Result) {
25	res.Code    = 500
26	res.Message = "fail"
27}
28
29func toJson (res *Result) {
30	jsons, errs := json.Marshal(res)
31	if errs != nil {
32		fmt.Println("json marshal error:", errs)
33	}
34	fmt.Println("json data :", string(jsons))
35}