当前位置:网站首页>[go ~ 0 to 1] day 4 June 30 defer, structure, method
[go ~ 0 to 1] day 4 June 30 defer, structure, method
2022-07-01 19:27:00 【Autumn sunset】
1. defer Delay call
take defer Later statements delay execution , It will save the state of execution when changing the line of code ( Changes in subsequent values of variables do not affect ) It is mainly used for the release of resources similar Java Medium finally
func defermethod() {
fmt.Println(" The first to perform ")
defer fmt.Println(" Finally, execute ")
fmt.Println(" Second, implementation ")
defer fmt.Println(" The penultimate execution execution ")
}
Output results by : The first to perform -> Second, implementation -> The penultimate execution execution -> The first to perform
matters needing attention :
There are more than one... In the function defer when , Will adopt First in, then out ( Declare first and then execute , queue )
defer It will keep the state when running to this line of code Although the implementation will be delayed
i := 10
defer fmt.Println(i)
i = 20
For example, the above code The final print result of the console is still 10
2. Structure
2.1 What is a structure
The structure is interpreted as Combine one or more variables together , Form a new type , This type is the structure
Java The essence of class in is Go The structure of language however Go The structure in a language is a reference type and Java Class in Is the reference data type
2.2 Declaration and assignment of structure
type Structure name struct{
Field one Type of field one
Field 2 Type of field 2
}
// Declare the structure first
type Person struct {
name string
age int
}
// To assign a value
var no1 Person
no1.name = " Zhang San "
no1.age = 19
fmt.Println(no1)
// Assign values while declaring the structure
type Person struct {
name string
age int
}
p1 := Person{
name: " Zhang San ",
age: 19,
}
fmt.Println(p1)
Be careful : The structure field without assignment will use the default value
2.3 Structure pointer
A structure is a value type , All assignments are copies
When there are many structural fields , In order to reduce memory, structure pointers can be passed
2.4 Constructors
type studnet struct {
name string
age int
}
func structmethod(name string, age int) studnet {
return studnet{
name: name,
age: age,
}
}
3. Structure and JSON Transformation
3.1 serialize
// Structure
type teach struct {
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
}
func serialmethod() {
// Create an object and assign a value
t1 := teach{
Name: " Mr. Zhang San ",
Age: 23,
}
// serialize
marshal, err := json.Marshal(t1)
if err != nil {
panic(err)
}
fmt.Println(string(marshal))
}
3.2 Deserialization
func unserialmethod() {
str := "{\"name\":\" Miss Zhang Si \",\"age\":24}"
// Create objects
var t2 teach
// Deserialization Be careful Need to transmit t2 Object reference address Otherwise you can't change t2 Value
err := json.Unmarshal([]byte(str), &t2)
if err != nil {
panic(err)
}
fmt.Println(t2)
}
4. Method
4.1 Method definition
stay Go In language , Functions and methods are different , There is a clear conceptual distinction . In other languages , such as Java, Generally speaking, a function is a method , The method is the function , But in Go In language , Function means that it doesn't belong to any structure 、 Method of type , In other words, the function has no receiver ; And the method has a receiver , The method we are talking about belongs to a structure , Of a newly defined type .
Method declaration is similar to function , The difference between them is : Method when defined , Will be in func Add a parameter between and method name , This parameter is the receiver , In this way, the method we defined is bound to the receiver , The way to call it this recipient .
Method recipients usually use lowercase of the type
// Structure
type China struct {
City string `json:"city,omitempty"`
Popu int `json:"popu,omitempty"`
}
// Serialization method
func (c China) seriMethod() []byte {
// Serialize the structure
marshal, err := json.Marshal(c)
if err != nil {
panic(err)
}
return marshal
}
// Deserialization method
func unseriMethod(bts []byte) China {
var cnew China
json.Unmarshal(bts, &cnew)
return cnew
}
边栏推荐
- Write it down once Net travel management background CPU Explosion Analysis
- Lumiprobe cell imaging study PKH26 cell membrane labeling kit
- MySQL常用图形管理工具 | 黑马程序员
- Three simple methods of ES6 array de duplication
- Solidity - truncated and checked modes of arithmetic operations - new features of 0.8.0
- 【英语语法】Unit1 冠词、名词、代词和数词
- Learning notes [Gumbel softmax]
- 小红书上的爱情买卖
- Solidity - 算术运算的截断模式(unchecked)与检查模式(checked)- 0.8.0新特性
- DTD建模
猜你喜欢
混沌工程平台 ChaosBlade-Box 新版重磅发布
制造业SRM管理系统供应商全方位闭环管理,实现采购寻源与流程高效协同
Huawei cloud experts explain the new features of gaussdb (for MySQL)
Lumiprobe cell imaging study PKH26 cell membrane labeling kit
Lake Shore M91快速霍尔测量仪
More information about M91 fast hall measuring instrument
SuperOptiMag 超导磁体系统 — SOM、SOM2 系列
C-end dream is difficult to achieve. What does iFLYTEK rely on to support the goal of 1billion users?
nacos启动失败问题解决与总结
云服务器ECS夏日省钱秘籍,这次@老用户快来领走
随机推荐
原生js打造日程表-支持鼠标滚轮滚动选择月份-可以移植到任何框架中
Supervarimag superconducting magnet system SVM series
Cache problems after app release
Love business in Little Red Book
Lumiprobe 亚磷酰胺丨六甘醇亚磷酰胺说明书
Once the SQL is optimized, the database query speed is increased by 60 times
Lake shore optimag superconducting magnet system om series
[pytorch record] automatic hybrid accuracy training torch cuda. amp
Gameframework eating guide
[AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?
白盒加密技术浅理解
Go language self-study series | go language data type
论文泛读【FiLM: Visual Reasoning with a General Conditioning Layer】
Netease games, radical going to sea
CDGA|从事通信行业,那你应该考个数据管理证书
Mipi interface, DVP interface and CSI interface of camera [easy to understand]
【直播预约】数据库OBCP认证全面升级公开课
Reading the paper [learning to discretely compose reasoning module networks for video captioning]
Solidity - 合约结构 - 错误(error)- ^0.8.4版本新增
Bao, que se passe - t - il si le serveur 100 + O & M a mal à la tête? Utilisez le majordome xingyun!