当前位置:网站首页>[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
}
边栏推荐
- 【直播预约】数据库OBCP认证全面升级公开课
- Contos 7 set up SFTP to create users, user groups, and delete users
- ECS summer money saving secret, this time @ old users come and take it away
- 【To .NET】C#集合类源码解析
- Supervarimag superconducting magnet system SVM series
- 【pytorch记录】自动混合精度训练 torch.cuda.amp
- 赋能「新型中国企业」,SAP Process Automation 落地中国
- Cache problems after app release
- Chaos engineering platform chaosblade box new heavy release
- Shell array
猜你喜欢
Lake Shore - crx-em-hf low temperature probe station
Dlib+Opencv库实现疲劳检测
XML syntax, constraints
M91 fast hall measuring instrument - better measurement in a shorter time
Games202 operation 0 - environment building process & solving problems encountered
机械设备行业数字化供应链集采平台解决方案:优化资源配置,实现降本增效
The former 4A executives engaged in agent operation and won an IPO
nacos启动失败问题解决与总结
从零开始学 MySQL —数据库和数据表操作
Junit单元测试框架详解
随机推荐
Lake Shore—CRX-EM-HF 型低温探针台
Lake Shore—OptiMag 超导磁体系统 — OM 系列
线程的并行、并发、生命周期
精益思想:来源,支柱,落地。看了这篇文章就懂了
Boost the development of digital economy and consolidate the base of digital talents - the digital talent competition was successfully held in Kunming
奔赴山海之前,毕业季一定要做的那些事情
[pytorch record] distributed training dataparallel and distributeddataparallel of the model
ETL development of data warehouse (IV)
[AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?
M91 fast hall measuring instrument - better measurement in a shorter time
Lumiprobe 活性染料丨吲哚菁绿说明书
Write it down once Net travel management background CPU Explosion Analysis
Yyds dry inventory ravendb start client API (III)
Today, with the popularity of micro services, how does service mesh exist?
Dom4J解析XML、Xpath检索XML
indexof和includes的区别
The difference between indexof and includes
Enabling "new Chinese enterprises", SAP process automation landing in China
MySQL常用图形管理工具 | 黑马程序员
苹果产品在日本全面涨价,iPhone13涨19%