When I was reading: http://golang.org/doc/effective_go.html#errors
I found such line: err.(*os.PathError)
in this context:
for try := 0; try < 2; try++ {
file, err = os.Create(filename)
if err == nil {
return
}
if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC {
deleteTempFiles() // Recover some space.
continue
}
return }
What exactly is err.(*os.PathError)
in Go?
Errors in Golang This is an unwanted condition and is therefore represented using an error. package main import ( "fmt" "ioutil" ) func main() { dir, err := ioutil.TempDir("", "temp") if err != nil { return fmt.Errorf("failed to create temp dir: %v", err) } }
Custom Errors in Golang In Go, we can create custom errors by implementing an error interface in a struct. Here, the Error() method returns an error message in string form if there is an error. Otherwise, it returns nil . Now, to create a custom error, we have to implement the Error() method on a Go struct.
os.Create
returns an error as second return value. The error itself is an interface type error interface { Error() string }
. Any data type that happens to have a Error
method will implement that interface and can be assigned.
In most cases, just printing the error is enough, but in this example, you would like to handle ENOSPC
(no space left on device) explicitly. The os
package returns an *os.PathError
as error implementation in that case and if you want to access additional information about the error, i.e. everything beside the Error() string
, method, you would have to convert it.
The statement e, ok := err.(*os.PathError)
is a type assertion. It will check if the interface value err
contains a *os.PathError
as concrete type and will return that. If another type was stored in the interface (there might be other types that implement the error
interface) then it will simply return the zero value and false, i.e. nil, false
in that case.
From the docs, that is a type assertion:
For an expression x of interface type and a type T, the primary expression
x.(T)
asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With