当前位置:网站首页>[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
边栏推荐
- Manipulator motion planning in 3C assembly
- [go]常见的并发模型[泛型版]
- CTF attack and defense world brush questions 51-
- Quick rehearsal exercise
- BUUCTF [极客大挑战 2019]EasySQL1
- 1216_ MISRA_ C standard learning notes_ Rule requirements for control flow
- Alibaba sentinel learning QA
- Research on system and software security (I)
- sql 使用过的查询语句
- 数据库之Mysql——概述安装篇
猜你喜欢

Intranet penetration series: icmptunnel of Intranet tunnel (Master James Barlow's)

浏览器中的 Kubernetes 和 IDE | 交互式学习平台Killercoda

使用 Ingress 实现金丝雀发布

Attack and defense world misc questions 1-50

Thinkphp6 + JWT realizes login verification

云计算技能大赛 -- openstack私有云环境 第一部分

Anti shake and throttling

feign如何集成hystrix

分布式服务治理Nacos

Briefly describe the hierarchical strategy of memory
随机推荐
MySQL——第一章节(MySQL中的数据类型)
Jetson Xavier NX(3)Bazel Mediapipe 安装
Upload labs range practice
Codeforces Round #784 (Div. 4)
BUUCTF [极客大挑战 2019]EasySQL1
为什么会存在1px问题?怎么解决?
Mobile web (Font Icon, plane conversion, color gradient)
渗透测试面试合集---HVV---
一个没啥L用,但可以装X的IDEA插件
Hierarchical output binary tree
Implementation principle of instanceof
The whole house intelligence bet by the giant is driving the "self revolution" of Hisense, Huawei and Xiaomi
Find the largest of 3 strings (no more than 20 characters per string).
Research on system and software security (3)
[go] common concurrency model [generic version]
利用Js实现一个千分位
Penetration test interview collection -- HVV---
AAAI 2022招募讲者啦!!
Positioning and decoration style
编译原理题-带答案