Example analysis of GO language Defer usage
- 2020-05-19 05:00:03
- OfStack
This article illustrates the use of the GO language, Defer. Share with you for your reference. The specific analysis is as follows:
defer: calls to a function that is defer are executed late, just before the function returns. This is a different, but effective, way to handle when a resource must be freed, no matter how the function returns. Traditional examples include unlocking a mutex or closing a file.
This delay of 1 function has two advantages: 1 is that you never forget to close the file, which often happens when you edit the function later to add a return path. Two is close and open next to one, which is much clearer than at the end of a function.
/**
* Created with IntelliJ IDEA.
* To change this template use File | Settings | File Templates.
* Name:Defer
*/
package main
import (
"fmt"
"os"
"log"
"io"
)
// Take the file content as 1 String return
func Contents(filename string) (string) {
// Open the file
f, err := os.Open(filename)
if err != nil {
log.Printf("%s",err)
}
fmt.Println("Close before >",f)
// if f.Close We're done here. So use DEFER Delay to perform
// He should be here f.Read() Execute after receiving ( I understand.)
defer f.Close()
fmt.Println("Close after >",f)
var result []byte
buf := make([]byte, 100)
for {
n, err := f.Read(buf[0:])
result = append(result, buf[0:n]...)
if err != nil {
if err == io.EOF {
break
}
log.Printf(" Not received all closed f>%s",err) // if f It's off ahead of time. Print
}
}
return string(result)
}
func main() {
fileurl := os.Getenv("HOME")
filename := fileurl+"/test.txt"
fmt.Println(Contents(filename))
}
We can better take advantage of the delayed execution of functions
/**
* Created with IntelliJ IDEA.
* To change this template use File | Settings | File Templates.
* Name:Defer
*/
package main
import (
"fmt"
)
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()
}
I hope this article has helped you with the programming of Go language.