当前位置:网站首页>[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
边栏推荐
猜你喜欢
Guoji Beisheng openstack container cloud environment construction
LeetCode 1611. 使整数变为 0 的最少操作次数
Ctf-misc learning from start to give up
Go语学习笔记 - 结构体 | 从零开始Go语言
Canvas learning Chapter 1
Brief description of CPU
1216_ MISRA_ C standard learning notes_ Rule requirements for control flow
Ribbon start process
nn.Module类的讲解
Go语学习笔记 - Slice、Map | 从零开始Go语言
随机推荐
NIH降血脂指南《your guide to lowering your Cholesterol with TLC》笔记(持续更新中)
三星,再次“西征”
Asynchronous learning
Draw a circle quickly in MATLAB (the one that can be drawn directly given the coordinates and radius of the center of the circle)
C语言学习记录——삼십팔 字符串函数使用和剖析(2)
Positioning of high precision welding manipulator
数据库之MySQL——基础篇
Hierarchical output binary tree
Reverse linked list exercise
Compiler des questions de principe - avec des réponses
[programming practice / embedded competition] learning record of embedded competition (II): picture streaming based on TCP
Cloud computing skills competition -- the first part of openstack private cloud environment
Canvas learning Chapter 1
How to import Excel data in SQL server, 2019 Edition
在线YAML转XML工具
Hump naming object
3C装配中的机械臂运动规划
PHP generates short links: convert numbers to letters and letters to numbers
Alibaba sentinel learning QA
Intranet penetration series: dnscat2 of Intranet tunnel