I'm new to Go (spent 30mins so far!) and am trying to do File I/O.
file, ok := os.Open("../../sample.txt")
if ok != nil {
// error handling code here
os.Exit(1)
}
...
When the call fails, shouldn't it return an error number? This call returns os.Error and it has no methods other than 'String()'.
Is this the recommended way to check for errors in Go?
Typical Go code (which uses the os
package) is not analyzing the returned error object. It just prints the error message to the user (who then knows what went wrong based on the printed message) or returns the error as-is to the caller.
If you want to prevent your program from opening a non-existent file, or want to check whether the file is readable/writable, I wound suggest to use the os.Stat function prior to opening the file.
Your can analyze the Go type of the returned error, but this seems inconvenient:
package main
import "fmt"
import "os"
func main() {
_, err := os.Open("non-existent")
if err != nil {
fmt.Printf("err has type %T
", err)
if err2, ok := err.(*os.PathError); ok {
fmt.Printf("err2 has type %T
", err2.Error)
if errno, ok := err2.Error.(os.Errno); ok {
fmt.Fprintf(os.Stderr, "errno=%d
", int64(errno))
}
}
fmt.Fprintf(os.Stderr, "%s
", err)
os.Exit(1)
}
}
which prints:
err has type *os.PathError
err2 has type os.Errno
errno=2
open non-existent: no such file or directory
Yes this is the normal way in Go (multi-value return), the makers of Go have a different view on Exceptions and handle it in this way.
Read this: