Some standard packages do so. For example, net/http.Client.Do may returns a non-nil *http.Reponse on error. But for such case, you don't need to call (*http.Response).Body.Close(), the http package has already closed it before returning it. So the principle is, if a non-nil value is returned on error, the caller should be able to ignore it safely.
On Saturday, April 1, 2017 at 6:33:39 AM UTC+8, Axel Wagner wrote: > > Hey gophers, > > there recently was a thread on /r/golang, about whether or not to > explicitly return useless values when an error occurred, or to just not > care, as the caller isn't supposed to use a return value on a non-nil value > anyway. So, say, I have a type that wraps an *os.File (or a database > handle, or such). And has some method that initializes state. Which is > better: > > func OpenFoo(fname string) (*Foo, error) { > f := &Foo{} > if err := f.initializeState(f, fname); err != nil { > return nil, err > } > return f, nil > } > > or > > func OpenFoo(fname string) (*Foo, error) { > f := &Foo{} > return f, f.initializeState(f, fname) > } > > (leaving aside both whether it's a good pattern to have such a separate > initialization method or not and whether to first assign its result to a > variable and then return that). > > I usually prefer the former; while it's true that the return value > shouldn't matter in the error-case as there is no guarantee about it, I > don't think it costs anything to explicitly return nil in that case and > thus make sure, that if a caller does forget that rule, they will simply > crash, instead of continuing with a value in an invalid state. > > Other people seem to feel very differently, very strongly. Their argument > seems to be a) that the zero value should be useful anyway and b) "I am > complicating things and should just check the error". I want to emphasize > that I agree with both of these rules, just that *if* I can't make the > zero value useful (and if it is, why would I need a constructor at all?), > there isn't a cost to also explicitly return something that will blow up > quickly in the error case, so that *if* the user of my package (or I) > accidentally not do the error-check correctly, it will make it a tiny bit > easier to debug. > > As this seems to be a not un-contentious issue and is also something I > regularly suggest in code-reviews for colleagues to do, I would like to > solicit further opinions on this; am I being unreasonable? Am I > recommending practices that makes worse go devs? > -- 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.