Several pitfalls that you may encounter when using defer

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Go's defer statement has a great effect on improving code readability. In some cases, however, defer's behavior can easily be confusing and difficult to clarify quickly. Although the author has been using go for more than two years, he will still be defer. My plan is to put together a series of behaviors that have puzzled me in the past, as a warning to myself. # # Defer scope is a function, not a statement block a variable exists only within the scope of a block of statements. The statement block where the defer statement is located will only be executed when the function returns. I don't know the rationale behind it, but if you allocate resources in a loop, and then use defer to reclaim resources, there is a risk of unintended disaster. Gofunc Do (files []string) error {for _, File: = Range files {f, err: = OS. Open (file) if err! = Nil {return err}defer f.close ()//This is the wrong usage!! Use F}} "(Translator Note: The above code will cause the loop to be recycled before starting to reclaim resources, rather than performing a loop to reclaim resources once) # # method chain If you are chaining methods in a defer statement, the rest of the functions are executed directly on the call, except for the last function. Defer requires a function as a "parameter". "' Gotype logger struct {}func (l *logger) Print (s string) {Fmt. Printf ("Log:%v\n", s)}type foo struct {L *logger}func (f *foo) logger () *logger {fmt. Println ("Logger ()") return F.l}func do (f *foo) {defer F.logger (). Print ("Done") fmt. Println ("Do")} Func main () {f: = &foo{l: &logger{},}do (f)} "output--" ' Logger () Dolog:done ' "logger () function in Do () function has been executed before. # # function Parameters Well, what happens if the last function receives a parameter?? In common sense, if it is executed after the peripheral function returns, any modification to the variable will be captured,Is it really as we expected? "' Gotype logger struct {}func (l *logger) Print (err error) {FMT. Printf ("Log:%v\n", err)}type foo struct {L *logger}func (f *foo) logger () *logger {fmt. Println ("Logger ()") return F.l}func do (f *foo) (err error) {defer F.logger (). Print (Err) fmt. Println ("Do") return to FMT. Errorf ("ERROR")} Func main () {f: = &foo{l: &logger{},}do (f)} "" Guess what the output is? "' Logger () Dolog: The value of <nil> ' err is still the value of the call defer. Any modifications to this variable are not captured by the defer statement because they do not point to the same value. # # # Calling functions for non-pointer types we have seen the execution characteristics of chained methods in defer statements. Further down, if the called method is not defined on a pointer type, a new instance will be copied in the defer statement. "' Gotype metrics struct {success boollatency time. Duration}func (M metrics) Log () {fmt. Printf ("Success:%v, Latency:%v\n", M.success, m.latency)}func foo () {var m metricsdefer M.Log () Start: = time. Now ()//Do somethingtime. Sleep (2*time. Second) m.success = Truem.latency = time. Now (). Sub (start)} ' output result ' ' Success:false, latency:0s ' when the defer statement executes, M is copied. M.foo () is a shorthand form of Foo (m). # # Conclusion If you use go for long enough, these may not be "traps". But for beginners, many parts of the defer statement do not conform to the [least surprising principle] (https://en.wikipedia.org/wiki/principle_of_least_astonishment). and [More] (http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/) [Many] (https://studygolang.com/ articles/12061) [Ground] (https://studygolang.com/articles/12136) [square] (https://studygolang.com/articles/12319) delves into the use of Go Common mistakes that you may encounter. Welcome to read.

via:https://medium.com/@i0exception/some-common-traps-while-using-defer-205ebbdc0a3b

Author: Aniruddha Translator: Sunzhaohao proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

402 Reads

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.