What is the use deferin golang? The language documentation says that it runs when the surrounding function returns. Why not just put the code at the end of this function?
defer
Usually we use deferto close or free resources.
The surrounding function makes all pending function calls before returning, even if it panics. If you simply put a function call at the end of the surrounding function, it is skipped when panic occurs.
Moreover, a deferred function call can cope with panic by calling a built-in function recover. This cannot be done by a normal function call at the end of a function.
recover
, . .
defer .
try-catch-finally.
try-catch-finally
try-finally:
try-finally
func main() { f, err := os.Create("file") if err != nil { panic("cannot create file") } defer f.Close() // no matter what happens here file will be closed // for sake of simplicity I skip checking close result fmt.Fprintf(f,"hello") }
func main() { defer func() { msg := recover() fmt.Println(msg) }() f, err := os.Create(".") // . is a current directory if err != nil { panic("cannot create file") } defer f.Close() // no matter what happens here file will be closed // for sake of simplicity I skip checking close result fmt.Fprintf(f,"hello") }
try-catch-finally . .
finally, , .
func yes() (text string) { defer func() { text = "no" }() return "yes" } func main() { fmt.Println(yes()) }
, , (, - ). defer , , , , .
defer esp. , esp . (, , ), , , . , , , , . , , close return). defer , , , , , , , .
. : , , , , , .
, Go - https://blog.learngoprogramming.com/golang-defer-simplified-77d3b2b817ff
defer - , , . , .
:
panic. , try... catch .
panic
try... catch
( , ..) . - , . , . . - .
. .
func BillCustomer(c *Customer) error { c.mutex.Lock() defer c.mutex.Unlock() if err := c.Bill(); err != nil { return err } if err := c.Notify(); err != nil { return err } // ... do more stuff ... return nil }
defer , , BillCustomer, mutex unlocked BillCustomer. , defer , unlock mutex , return.
BillCustomer
mutex
unlocked
unlock
return
defer :
func elapsed(what string) func() { start := time.Now() fmt.Println("start") return func() { fmt.Printf("%s took %v\n", what, time.Since(start)) } } func main() { defer elapsed("page")() time.Sleep(time.Second * 3) }
start page took 3s
Source: https://habr.com/ru/post/1690170/More articles:Положительный lookbehind для не-ASCII символов в R - regexExecuting a foreach block simultaneously for all elements? - c #How to simplify my code using stream or lambda - javaFinding data for current date in SQL Server - sqlC # async / awaiting progress report not in expected order - c #https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1690171/python-interpreter-takes-12-seconds-to-start-up-all-of-which-is-spent-in-import-pyexpat&usg=ALkJrhh2YDH1geep8i1nQRLb5CtTCasdZQionic 2 Offline Data synchronization using Azure Mobile Apps throws TypeError: Cannot read openDatabase property from undefined - sqliteA related service error using "Context.startForegroundService () did not cause a Service.startForeground () error" - androidChecking if the binary tree is also a binary search tree - javaAccess Gmail (or a secure website) without getting a PKIX certification path error - javaAll Articles