结构体是将零个或多个任意类型的变量,组合在一起的聚合数据类型,也可以看做是数据的集合。
//demo_11.gopackage mainimport ("fmt")type Person struct {Name stringAge int}func main() {var p1 Personp1.Name = "Tom"p1.Age = 30fmt.Println("p1 =", p1)var p2 = Person{Name:"Burke", Age:31}fmt.Println("p2 =", p2)p3 := Person{Name:"Aaron", Age:32}fmt.Println("p2 =", p3)//匿名结构体p4 := struct {Name stringAge int} {Name:"匿名", Age:33}fmt.Println("p4 =", p4)}
运行结果:
//demo_12.gopackage mainimport ("encoding/json""fmt")type Result struct {Code int `json:"code"`Message string `json:"msg"`}func main() {var res Resultres.Code = 200res.Message = "success"//序列化jsons, errs := json.Marshal(res)if errs != nil {fmt.Println("json marshal error:", errs)}fmt.Println("json data :", string(jsons))//反序列化var res2 Resulterrs = json.Unmarshal(jsons, &res2)if errs != nil {fmt.Println("json unmarshal error:", errs)}fmt.Println("res2 :", res2)}
运行结果:
//demo_13.gopackage mainimport ("encoding/json""fmt")type Result struct {Code int `json:"code"`Message string `json:"msg"`}func main() {var res Resultres.Code = 200res.Message = "success"toJson(&res)setData(&res)toJson(&res)}func setData (res *Result) {res.Code = 500res.Message = "fail"}func toJson (res *Result) {jsons, errs := json.Marshal(res)if errs != nil {fmt.Println("json marshal error:", errs)}fmt.Println("json data :", string(jsons))}
运行结果: