No, method 1 preserves "err" if it is not nil.

Tong Sun <suntong...@gmail.com> ezt írta (időpont: 2016. okt. 17., H 20:11):

>
> On Mon, Oct 17, 2016 at 1:20 AM, Tamás Gulácsi wrote:
>
>
>
> The reason that I didn't do it, is because I don't know how to do it. In
> essence, that "f.Close()" that you worried about is wrapped in "defer
> f.Close()" in SaveState, which in turn wrapped in "defer SaveState" in a
> function. I.e., all is happening during the program tear-down phase. If we
> are not planting a "log.Fatal(err)" bomb in SaveState itself, how do you
> think we should check it properly?
>
>
> There are several possibilities. Two easy:
> 1. use a named return parameter:
> func SaveState(...) (err error) {
> ...
> // close the file and return the error
> defer func() {
>   if closeErr := f.Close(); closeErr != nil && err == nil {
>     err = closeErr
> }()
> ...
> }
>
>
> That method will interfere with/overwrite the existing return logic right?
>
> Basically, my "func SaveState(...) error" has "return gob.NewEncoder(f).
> Encode(state)" as the last statement:
>
> func SaveState(persistName string, state interface{}) error {
> // create persistence file
> f, err := os.Create(persistName)
> if err != nil {
> return err
> }
> defer f.Close()
> // write persistemce file
> err = gob.NewEncoder(f).Encode(state)
> return err
> }
>
> if using the method 1, then if the gob.NewEncoder(f).Encode(state) fails,
> but defer f.Close() works, the true error will be lost, right?
>
>
> 2. Treat the defer f.Close() just as a resource releaser for error path,
> and do an "return f.Close()" anyway:
> func SaveState(...) error {
> ...
> defer f.Close() // just release resources on error paths
> ...
> return f.Close() // never lose the error of Close!
> }
>
> yes, this does call f.Close() twice, and the second (the defer) will error
> out, but that does no harm.
>
>
> OK, will try to do that, and report back...
>
>

-- 
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.

Reply via email to