They also seem to be the only way to handle errors in defer <https://pocketgophers.com/handling-errors-in-defer/> without panic or log.Fatal.
On Wednesday, February 22, 2017 at 6:24:41 AM UTC+1, Paul Borman wrote: > > Named return values are perfectly fine, and I agree, probably should not > be discouraged. For example, which is easier to write documentation for? > > func Run(cmd string) ([]byte, []byte, error) > > func Run(cmd string) (stdout, stderr []byte, _ error) > > What is not good is the following function: > > func Foo() (err error) { > if err := someFunc(); err != nil { > return // Why do I always get a nil error?!?! > } > return > } > > This is a* naked return* and that is what is bad, not that you named your > return values. This version is fine: > > func Foo() (err error) { > if err := someFunc(); err != nil { > return err > } > return nil > } > > As there is no doubt on what is being returned. And as mentioned earlier, > named returns are very useful in defers: > > func Foo(path string) (err error) { > w, err := os.Create(path, 0644) > if err != nil { > return err > } > defer func() { > if cerr := w.Close(); cerr != nil && err == nil { > err = cerr > } > }() > ... > } > > > Again, named return values are fine and cause no problems, but naked > returns should never have been part of the language (at first they seem > useful and cool, but in the end, they cause more problems than they solve). > > On Tue, Feb 21, 2017 at 8:25 PM, <prade...@gmail.com <javascript:>> wrote: > >> Named returns are actually quite useful with panics : >> >> https://play.golang.org/p/ZdoZJBN0T1 >> >> >> Le mardi 21 février 2017 23:13:11 UTC+1, Ian Lance Taylor a écrit : >>> >>> On Tue, Feb 21, 2017 at 1:46 PM, <andrew.p...@gmail.com> wrote: >>> > Seems like named returns + if/for/switch initializers = a shadowing >>> > nightmare. I wish the Go compiler emitted a loud warning on shadowing, >>> as >>> > this is a dangerously subtle problem out there. >>> >>> Yes, named returns may have been a mistake. Only use them in very >>> very short functions. >>> >>> Ian >>> >> -- >> You received this message because you are subscribed to the Google Groups >> "golang-nuts" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to golang-nuts...@googlegroups.com <javascript:>. >> For more options, visit https://groups.google.com/d/optout. >> > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.