当前位置:网站首页>[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
}
边栏推荐
- SuperOptiMag 超导磁体系统 — SOM、SOM2 系列
- 论文阅读【Learning to Discretely Compose Reasoning Module Networks for Video Captioning】
- ECS summer money saving secret, this time @ old users come and take it away
- 使用环信提供的uni-app Demo,快速实现一对一单聊
- Bao, que se passe - t - il si le serveur 100 + O & M a mal à la tête? Utilisez le majordome xingyun!
- transform + asm资料
- 【pytorch记录】自动混合精度训练 torch.cuda.amp
- Dom4j parsing XML, XPath retrieving XML
- Solidity - 合约结构 - 错误(error)- ^0.8.4版本新增
- 智慧防疫系统为建筑工地复工复产提供安全保障
猜你喜欢

市值蒸发740亿,这位大佬转身杀入预制菜

白盒加密技术浅理解

Lumiprobe free radical analysis h2dcfda instructions

网易游戏,激进出海

前4A高管搞代运营,拿下一个IPO

ubuntu14安装MySQL并配置root账户本地与远程访问

Huawei game failed to initialize init with error code 907135000

水产行业智能供应链管理平台解决方案:支撑企业供应链数字化,提升企业管理效益

Detailed explanation of JUnit unit test framework

Manufacturing SRM management system supplier all-round closed-loop management, to achieve procurement sourcing and process efficient collaboration
随机推荐
网易游戏,激进出海
Getting started with kubernetes command (namespaces, pods)
Enabling "new Chinese enterprises", SAP process automation landing in China
Parallelism, concurrency and life cycle of threads
CDGA|从事通信行业,那你应该考个数据管理证书
Transform + ASM data
How to redraw the header of CListCtrl in MFC
The best landing practice of cave state in an Internet ⽹⾦ financial technology enterprise
Docker deploy mysql8.0
11. Users, groups, and permissions (1)
助力数字经济发展,夯实数字人才底座—数字人才大赛在昆成功举办
Prices of Apple products rose across the board in Japan, with iphone13 up 19%
使用环信提供的uni-app Demo,快速实现一对一单聊
Three ways for redis to realize current limiting
Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
Superoptimag superconducting magnet system - SOM, Som2 series
241. Different Ways to Add Parentheses
[to.Net] C set class source code analysis
Lake Shore—OptiMag 超导磁体系统 — OM 系列
indexof和includes的区别