当前位置:网站首页>【Go ~ 0到1 】 第四天 6月30 defer,结构体,方法
【Go ~ 0到1 】 第四天 6月30 defer,结构体,方法
2022-07-01 18:43:00 【秋日的晚霞】
1. defer 延迟调用
将defer 后面的语句延迟执行 , 会把执行当改行代码时的状态保存下来(变量后续值的变化不会影响) 多用于资源的释放 类似Java中的 finally
func defermethod() {
fmt.Println("最先执行")
defer fmt.Println("最后执行")
fmt.Println("第二执行")
defer fmt.Println("倒数第二执行执行")
}
输出结果 为 : 最先执行 -> 第二执行 -> 倒数第二执行执行 -> 最先执行
注意事项 :
函数中有多个defer时,将采用 先进后出 (先声明的后执行,队列)
defer会保留运行到这一行代码时的状态 虽然会延迟执行
i := 10
defer fmt.Println(i)
i = 20
例如上述代码 最终控制台的打印结果仍然为 10
2. 结构体
2.1 什么是结构体
结构体解释为 将一个或多个变量组合到一起, 形成一个新的类型,这个类型就是结构体
Java中的类本质就是Go语言的结构体 但是 Go语言中的结构体是引用类型 而 Java中的类 是引用数据类型
2.2 结构体的声明与赋值
type 结构体名 struct{
字段一 字段一的类型
字段二 字段二的类型
}
//先声明结构体
type Person struct {
name string
age int
}
// 再赋值
var no1 Person
no1.name = "张三"
no1.age = 19
fmt.Println(no1)
//声明结构体的同时赋值
type Person struct {
name string
age int
}
p1 := Person{
name: "张三",
age: 19,
}
fmt.Println(p1)
注意 : 没有赋值的结构体字段会使用默认值
2.3 结构体指针
结构体是值类型,赋值的时候都是拷贝
当结构体字段较多的时候,为了减少内存可以传递结构体指针
2.4 构造函数
type studnet struct {
name string
age int
}
func structmethod(name string, age int) studnet {
return studnet{
name: name,
age: age,
}
}
3. 结构体与JSON的转换
3.1 序列化
// 结构体
type teach struct {
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
}
func serialmethod() {
//创建对象并赋值
t1 := teach{
Name: "张三老师",
Age: 23,
}
//序列化
marshal, err := json.Marshal(t1)
if err != nil {
panic(err)
}
fmt.Println(string(marshal))
}
3.2 反序列化
func unserialmethod() {
str := "{\"name\":\"张四老师\",\"age\":24}"
//创建对象
var t2 teach
//反序列化 注意 需要传t2对象的引用地址 否则不能改变 t2 的值
err := json.Unmarshal([]byte(str), &t2)
if err != nil {
panic(err)
}
fmt.Println(t2)
}
4.方法
4.1 方法的定义
在Go语言中,函数和方法不太一样,有明确的概念区分。其他语言中,比如Java,一般来说函数就是方法,方法就是函数,但是在Go语言中,函数是指不属于任何结构体、类型的方法,也就是说函数是没有接收者的;而方法是有接收者的,我们说的方法要么是属于一个结构体的,要么属于一个新定义的类型的。
方法的声明和函数类似,他们的区别是:方法在定义的时候,会在func和方法名之间增加一个参数,这个参数就是接收者,这样我们定义的这个方法就和接收者绑定在了一起,称之为这个接收者的方法。
方法接受者通常使用类型的小写
// 结构体
type China struct {
City string `json:"city,omitempty"`
Popu int `json:"popu,omitempty"`
}
// 序列化方法
func (c China) seriMethod() []byte {
//将结构体序列化
marshal, err := json.Marshal(c)
if err != nil {
panic(err)
}
return marshal
}
// 反序列化方法
func unseriMethod(bts []byte) China {
var cnew China
json.Unmarshal(bts, &cnew)
return cnew
}
边栏推荐
- The best landing practice of cave state in an Internet ⽹⾦ financial technology enterprise
- 【pytorch记录】模型的分布式训练DataParallel、DistributedDataParallel
- JS find the next adjacent element of the number in the array
- Is PMP cancelled??
- R language ggplot2 visualization: gganimate creates a dynamic histogram animation (GIF), and displays the histogram and enter step by step along a given dimension in the animation_ Growth function and
- 太爱速M源码搭建,巅峰小店APP溢价寄卖源码分享
- 11、用户、组和权限(1)
- 水产行业智能供应链管理平台解决方案:支撑企业供应链数字化,提升企业管理效益
- Golang error handling
- SuperVariMag 超导磁体系统 — SVM 系列
猜你喜欢
Leetcode-141 circular linked list
制造业SRM管理系统供应商全方位闭环管理,实现采购寻源与流程高效协同
Altair HyperWorks 2022软件安装包和安装教程
混沌工程平台 ChaosBlade-Box 新版重磅发布
Lake Shore - crx-em-hf low temperature probe station
6月刊 | AntDB数据库参与编写《数据库发展研究报告》 亮相信创产业榜单
Lumiprobe phosphide hexaethylene phosphide specification
11. Users, groups, and permissions (1)
Lake Shore低温恒温器的氦气传输线
Cdga | if you are engaged in the communication industry, you should get a data management certificate
随机推荐
Graduation summary
AI training speed breaks Moore's law; Song shuran's team won the RSS 2022 Best Paper Award
More information about M91 fast hall measuring instrument
How to use the low code platform of the Internet of things for personal settings?
混沌工程平台 ChaosBlade-Box 新版重磅发布
从零开始学 MySQL —数据库和数据表操作
transform + asm资料
Excel之VBA简单宏编程
Games202 operation 0 - environment building process & solving problems encountered
Taiaisu M source code construction, peak store app premium consignment source code sharing
实例讲解将Graph Explorer搬上JupyterLab
云服务器ECS夏日省钱秘籍,这次@老用户快来领走
Three ways for redis to realize current limiting
Lumiprobe phosphide hexaethylene phosphide specification
数据仓库(四)之ETL开发
Prices of Apple products rose across the board in Japan, with iphone13 up 19%
学习笔记-JDBC连接数据库操作的步骤
Intensive cultivation of channels for joint development Fuxin and Weishi Jiajie held a new product training conference
June issue | antdb database participated in the preparation of the "Database Development Research Report" and appeared on the list of information technology and entrepreneurship industries
Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse