当前位置:网站首页>[effective go Chinese translation] function
[effective go Chinese translation] function
2022-04-23 08:13:00 【Ling Xing an】
Functions
Multiple return values Multiple return values
Go The most unusual feature of functions and methods in is that they can return multiple variables . This form can improve C Some clumsy programming habits in programming , Returns an error -1 Express EOF , Pass the variable address to modify the variable .
stay C In language , Write errors are represented by negative error codes , Imperceptible . stay Go in ,Write You can return a count and an error : The device may mean that some data is written .
os The package Write The method signature of is :
func (file *File) Write(b []byte) (n int, err error)
Number of bytes written when n!=len(b) when , Will return a non nil Error of error ; This is a very common style .
This grammar , Avoids the need to pass pointers to simulate reference parameters as return values . Here's a simple function , Grab a byte from its slice , Returns the number and the next position .
func nextInt(b []byte, i int) (int, int) {
for ; i < len(b) && !isDigit(b[i]); i++ {
}
x := 0
for ; i < len(b) && isDigit(b[i]); i++ {
x = x*10 + int(b[i]) - '0'
}
return x, i
}
You can traverse like this slice Data in
eg:
for i := 0; i < len(b); {
x, i = nextInt(b, i)
fmt.Println(x)
}
Named result parameters Name the return value
Go The return value of the function in , You can name it , Use like regular variables and function parameters . Function execution time , The named return value will be initialized to the default value of the corresponding type . When executed return When the sentence is , The current named return value variable , Will be returned as a return value .
This naming is not mandatory , But it can make the code clearer .
above nextInt I could rewrite it as :
eg:
func nextInt(b []byte, pos int) (value, nextPos int) {
The named return value is initialized , And with simple return Statement Association , This style is simple and easy to understand .io.ReadFull This form is used in .
func ReadFull(r Reader, buf []byte) (n int, err error) {
for len(buf) > 0 && err == nil {
var nr int
nr, err = r.Read(buf)
n += nr
buf = buf[nr:]
}
return
}
Defer
Go Medium defer sentence Meeting arrangement Delay function When the function executes return Before calling . This is an uncommon but effective Solve the way that the function must release the requested resources in any case ,
Here is a classic case of releasing a lock or closing a file .
eg:
// Contents returns the file's contents as a string.
func Contents(filename string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close() // f.Close will run when we're finished.
var result []byte
buf := make([]byte, 100)
for {
n, err := f.Read(buf[0:])
result = append(result, buf[0:n]...) // append is discussed later.
if err != nil {
if err == io.EOF {
break
}
return "", err // f will be closed if we return here.
}
}
return string(result), nil // f will be closed if we return here.
}
Like above Close That deferred invocation has two advantages : 1. It ensures that you don't forget to close the file , This mistake is adding new return Time is easy to appear . 2. stay open After use close, It can make the code clearer .
Parameters of delay function Or the receiver of the method In execution defer The time to be determined , Instead of determining when the function executes . So don't worry about function execution , Change the parameters of the delay function . Again , It also means a defer Call can execute multiple delay functions .
eg:
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
The delay function is based on LIFO( Last in, first out ) The order of execution . So when the above function returns, print 4 3 2 1 0
demonstration :
package main
import "fmt"
func fun(){
fmt.Println("fun start")
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
fmt.Println("fun end")
return
}
func main() {
fun()
fmt.Println("main ...")
}
result :
fun start
fun end
4 3 2 1 0 main …
A more reasonable example is trace Execution of a function . We wrote several simple paths
eg:
func trace(s string) {
fmt.Println("entering:", s) }
func untrace(s string) {
fmt.Println("leaving:", s) }
// Use them like this:
func a() {
trace("a")
defer untrace("a")
// do something....
}
We can use perform defer Statement to determine the delay function parameters Characteristics Write better code .
eg:
func trace(s string) string {
fmt.Println("entering:", s)
return s
}
func un(s string) {
fmt.Println("leaving:", s)
}
func a() {
defer un(trace("a"))
fmt.Println("in a")
}
func b() {
defer un(trace("b"))
fmt.Println("in b")
a()
}
func main() {
b()
}
result :
entering: b
in b
entering: a
in a
leaving: a
leaving: b
For a programmer who is used to modular management of resources in other languages ,defer It looks very strange . But it's really an interesting and powerful application , To describe it more accurately, it is based on function , Not modularity . We can use panic and recover in , Another possibility to see it .
版权声明
本文为[Ling Xing an]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230648129815.html
边栏推荐
- 校园转转二手市场源码下载
- Attack and defense world misc questions 1-50
- Smart business card applet business card details page function implementation key code
- Ctf-misc learning from start to give up
- Buuctf misc brush questions
- The whole house intelligence bet by the giant is driving the "self revolution" of Hisense, Huawei and Xiaomi
- Samsung, March to the west again
- php生成短链接:将数字转成字母,将字母转成数字
- Research on system and software security (3)
- Positioning and decoration style
猜你喜欢
数据库之MySQL——基本常用查询命令
vivo,硬件安全的爱与雷霆
Feign源码分析
在MATLAB中快速画圆(给出圆心坐标和半径就能直接画的那种)
每周leetcode - 06 数组专题 7~739~50~offer 62~26~189~9
干货!以点为形:可微分的泊松求解器
云计算技能大赛 -- openstack私有云环境 第二部分
Intranet penetration series: dns2tcp of Intranet tunnel
Data security has become a hidden danger. Let's see how vivo can make "user data" armor again
【Appium】测试时遇到手机内嵌H5页面的切换问题
随机推荐
PHP generates short links: convert numbers to letters and letters to numbers
Usage of databinding
Go语学习笔记 - 结构体 | 从零开始Go语言
华硕笔记本电脑重装系统后不能读取usb,不能上网
Penetration test interview collection -- HVV---
[Effective Go 中文翻译]函数篇
Draw a circle quickly in MATLAB (the one that can be drawn directly given the coordinates and radius of the center of the circle)
DVWA靶场练习
yum源仓库本地搭建的两种方法
[go] common concurrency model [generic version]
Go语学习笔记 - 异常处理 | 从零开始Go语言
国基北盛-openstack-容器云-环境搭建
CTF attack and defense world brush questions 51-
Thinkphp6 + JWT realizes login verification
每周leetcode - 06 数组专题 7~739~50~offer 62~26~189~9
利用Js实现一个千分位
Ignis公链的NFT生态发展:Unicorn.art的捐赠开发之路
編譯原理題-帶答案
Ctf-misc learning from start to give up
LeetCode15. 三数之和