惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
F
Fortinet All Blogs
小众软件
小众软件
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
有赞技术团队
有赞技术团队
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
V
Visual Studio Blog
A
About on SuperTechFans
I
InfoQ
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
罗磊的独立博客
C
Check Point Blog
大猫的无限游戏
大猫的无限游戏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
MyScale Blog
MyScale Blog

jobcher on 打工人日志

2023-12-21 打工人日报 2023-12-20 打工人日报 2023-12-19 打工人日报 2023-12-18 打工人日报 2023-12-17 打工人日报 2023-12-16 打工人日报 2023-12-15 打工人日报 2023-12-14 打工人日报 2023-12-13 打工人日报 2023-12-12 打工人日报 2023-12-11 打工人日报 2023-12-10 打工人日报 2023-12-09 打工人日报 2023-12-08 打工人日报 2023-12-07 打工人日报 2023-12-06 打工人日报 2023-12-05 打工人日报 2023-12-04 打工人日报 2023-12-03 打工人日报 2023-12-02 打工人日报 2023-12-01 打工人日报 2023-11-30 打工人日报 2023-11-29 打工人日报 2023-11-28 打工人日报 2023-11-27 打工人日报 2023-11-26 打工人日报 2023-11-25 打工人日报 2023-11-24 打工人日报 2023-11-23 打工人日报 2023-11-22 打工人日报
go Struct 结构体
2022-04-26 · via jobcher on 打工人日志

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}