3 ms·
If I attempt to grab the result of a function eg: f := os.Create(fname) defer(f.Close()) It won't compile as `os.Create` returns `(file, error)`. So y
by hornetblack 13y ago
If I attempt to grab the result of a function eg:
f := os.Create(fname)
defer(f.Close())
It won't compile as `os.Create` returns `(file, error)`. So you must either:
// Proper error handling
f, err := os.Create(fname)
if err != nil {
log.Fatalf("Could not create '%s'", fname)
// Well may want to do something other than crash.
}
defer(f.close())
If you ignore the error it's obvious
f, _ := os.Create(fname)
defer(f.Close())
It's like doing this in Java
File f;
try {
f = new File(fname);
} catch (Exception e) {
// Ignore Exception
}
- drbawb 13y agoPossibly worth pointing out to non-gophers: in `Go` it is illegal to declare an unused variable. So if you write `f, err := os.Create("/bad/path");`, and that is the first time `err` has been declared & used in that scope, you can't just let `err` go unused or your program won't compile.