The defer of Go language

Source: Internet
Author: User
/*1 applies to functions and methods and can only be deferred to a method or function *//*2 defer statement until the function return or the Panicreturn function is not atomic, including the write return parameter and function return, defer statement executes before the function returns after writing the return parameter *//*3    Defer statement counter-order Execution (stack) is generally used adulthood to open, close, connect, disconnect, locking, release the lock release resources *//*4 defer statement where the variable into the stack, only the function ends and then process the statement, if the value is passed the subsequent value change does not affect the defer statement, If the address pass affects the Defer statement defer function arguments when the defer statement executes when the defer function call is executed 4.1 defer the entry and exit of the record function, the trace function *//*5 method is a data type, after the method is defined,  By assigning a value to a data type that has a method, the type of the method is the same as the assignment type, and you can perform a method operation *//*6 each time a "defer" statement executes, the function Valueand parameters to the Call be evaluated as Usualand saved Anewbut The actual function is not invoked.anew: Re-*//*7 defer function calls function return value and function input parameter according to normal function Processing (copying new parameters), the closure function variable updates the variable in the defer function, but the actual function is not activated. The procedure returned by the *//*8 function is this: assigning a value to the return value first, then calling the defer expression, and finally returning to the calling function. Use the closure defer function (pointer) to modify the value of the return value. *//*9 defer expression may modify the return value after the function return value is set, before returning to the calling function, so that the final function return value is inconsistent with your imagination *//*10 defer+ Panic non-panic function is performed normally by defer: defer definition, func return/panic execute deferpanic function only after panic statement does not execute *///package mainimport ("FMT" "Lo G "" Time ")//Definition method type Defmeth struct {err bool str string}//defines an interface for a data type that provides operation type in interface {iNi () prinout ()}func (def *defmeth) Ini () {Def.err = True def.str = "Hei"}func (def *defmeth) Prinout () {fmt. Println ("Just Print:", def)}type deferror struct {err error str string}func (def *deferror) Ini () {def.err = f Mt. Errorf ("This was a err:%s\n", "true") Def.str = "This is a Bug"}func (def *deferror) Prinout () {fmt. Println ("Just Print:", Def)}func main () {var s1 defmeth var S2 deferror var def in a: = 1//defer+ closed packet processing, a The DEFER function variable updates the defer func () {FMT) for the main function variable, a value change. PRINTLN ("Close package, test the value of a:", a)} () defer FMT. Println ("Fmt A is:", a)//value pass, defer function into the stack, the variable value is assigned, only the last execution defer func (a int) {FMT. Println ("No Name func A is:", a)} (a)//address delivery: The address is passed, if the value changes at the address, the operation value changes, map passes the address defer func (a *int) {fmt. Println ("No name Func a address is:", *a)} (&a)//For interface assignment variable type and variable address def = &s1//a:=1 Def.ini ()//defe R a=2//error defer must be a function or method or interface Def.prinout ()//fmt.  PRINTLN ("Result", bigslowoperation ())  The interface def = &s2 Def.ini ()///function defer changes the defer execution order, the function defer on the stack, the function performs def.prinout () a++ FMT normally. Println (a) fmt. Println ("The value of Bigslow func:", Bigslowoperation ())//10 test defer Panic deferpanic ()}func bigslowoperation ( ) int {log. Printf ("Main starts%s", "\ n") I: = 1//non-anonymous function call parameter I has determined: 1//defer fmt. PRINTLN (i)//anonymous function callable return value: 2 defer func () {fmt. Println (i)} () Defer trace ("Bigslowoperation") ()//don ' t forget the//extra parentheses//... lots of work ... t Ime. Sleep (Ten * time. Second)//simulate slow operation//by sleeping i++ return i}//returned value is function, function needs to be in the stack,//function input parameter and return address according to normal function,//defer trac E ("")///function is an anonymous function wrapped in trace, it is necessary to properly handle the function,//The formal parameter and return address Func trace (msg string) func () {start: = time. Now () log. Printf ("Enter%s", msg) return func () {log. Printf ("Exit%s (%s)", MSG, time.) Since (start))}}//10 Defer+panic:what Happends after a defer func panicfunc deferpanic () {//Normal execution defer FMT. Println ("The last defer pAnic func ") defer FMT. Println ("The 3st Defer Panic func")//panic Func executes only the panic statement defer func () {Panic ("Test defer panic"); Fmt. Println ("The Func Panics")} ()//normal execution defer FMT. Println ("The 2st Defer Panic func") defer FMT. Println ("The 1st Defer Panic Func")}

75 reads ∙1 likes
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.