3 ms·
> You can't just `defer f.Close()` after the first condition (regardless of flushing / write loss issues, we'll assume read-only) because you want to return it
by svnpenn 4y ago
> You can't just `defer f.Close()` after the first condition (regardless of flushing / write loss issues, we'll assume read-only) because you want to return it
You would never include Close in this function, period. In this example above,
it would always be the caller closing the file:
package main
import "os"
func hello() (*os.File, error) {
return os.Open("file.go")
}
func main() {
file, err := hello()
if err != nil {
panic(err)
}
defer file.Close()
}
- geraneum 4y agoThe problem is, the programmer (caller) forgets and that’s the whole point of having a more or less automated way of releasing/closing/etc. Apart from that, it’s bad design IMO (leaky abstraction).
- jjnoakes 4y agoThe example above has an operation that might fail between the Open and the return. Leaving that out of course makes the example useless, but if you keep that part in, you can't use go's simple defer pattern to help you close the file if that intermediate operation fails.
- tialaramex 4y agoNow though this extra work (the thing I got has to have deferred work done when I don't need it any more) is given to your caller. For a File Handle this might feel natural, but what about if I hand you a... 3D printer? a Bank Account? a Youtube Video? a Package Delivery? Which of these need some sort of "deferred close" action ? You probably need to read the docs and arrange to close or not close things accordingly right? You're going to be Wrong by Default again.
- masklinn 4y ago> In this example above, it would always be the caller closing the file: You missed the entire point, literally. Maybe try reading the original comment again?