golang之defer

Outline
For the release of resources, there are many different implementations, different languages ​​have different conventional methods.
  • C Language: Manual management
  • Golang: defer
  • Python: Context Manager contexManager
  • C ++: Scope and destructor
  • Rust: ownership and drop trait
If you know several languages ​​on top of the children's shoes should know,
C language resource management is more trouble once the error occurred during the use of the resource, it could cause resource leaks.
Golang through defer, even during the panic, you can free up resources.
Python via the context manager, two main function` Magic __enter__ `,` __exit__ `to ensure the release of resources.
Rust is similar to C ++ and are automatically calls the release function in some semantics. But there Rust ownership check, you can write code to prevent silly (such as C ++ accidentally copy a bit.)
 
 
The above point of view, C ++ and Rust must be in programming the timing of the release of attention, that is, the programmer needs more thought. But Rust compiler will help you, but C ++ does not.
Second, Python and Golang use explicit management must not forget to do, but do not be a big problem.
 
defer
But this is an article about derfer article, write about the focus defer to note (read Effective Go is little notes).
 
Basic use
` The defer statement function call scheduled for execution before the end of the current function. That is the function call defer statement is the last thing the current function performed `
- a classic example
 1 // Contents returns the file's contents as a string.
 2 func Contents(filename string) (string, error) {
 3     f, err := os.Open(filename)
 4     if err != nil {
 5         return "", err
 6     }
 7     defer f.Close()  // f.Close will run when we're finished.
 8 
 9     var result []byte
10     buf := make([]byte, 100)
11     for {
12         n, err := f.Read(buf[0:])
13         result = append(result, buf[0:n]...) // append is discussed later.
14         if err != nil {
15             if err == io.EOF {
16                 break
17             }
18             return "", err  // f will be closed if we return here.
19         }
20     }
21     return string(result), nil // f will be closed if we return here.
22 }
 
Using the above code words `translation of the defer f.Close () ` it is the "will f.Close () The last execution in the function of Contents"
The ` f.close () ` on the back defer has two advantages: to ensure that resources are released, from the more recent `Open` do not forget.
This is nothing to say, golang must explicitly release resources.
 
detail
First clear the two concepts
- defer statement execution
    The defer statement in a function call scheduled execution before the end of the current function
- the implementation of a function call
    Function call to run defer statement
 
Parameters evaluated
Here parameter evaluation refers to the parameter defer statement function call.
Parameters evaluated defer statement is executed, instead of seeking value at the time of the function call executed.
- Another example
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()
}

 

First look at the function B, because the parameters are executed at the defer statement is evaluated, the `trace (" b ")` is first evaluated [prints "b", and then return to "b"], then perform down before the end of the function b calls the `un (" b ")`.
The same function as a. Now I guess the results.
 
entering: b
in b
entering: a
in a
leaving: a
leaving: b
 
Execution order
When there are multiple defer statement, in the end who is the function call to enforce it?
 
1 for i := 0; i < 5; i++ {
2     defer fmt.Printf("%d ", i)
3 }

 Defer execution of the function call pressing the last in, first out (LIFO) manner. Probably guess, will defer to each function call onto the stack, the stack performs the last turn.

 
At last
golang in defer it is mainly used in the management of resources. More than a few points clear, should not the (bragging ing) problems.


 
 

Guess you like

Origin www.cnblogs.com/chyuwei/p/11082225.html