In Go's documentation on effective error handling (https://golang.org/doc/effective_go.html#errors), you may have encountered the code snippet:
<code class="go">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 }</code>
This code demonstrates the use of err.(*os.PathError). Let's delve into what it means.
When os.Create is called, it returns an error as its second return value. This error implements the error interface { Error() string }. Any data type that possesses an Error method can implement this interface and be assigned to it.
Typically, simply outputting the error message suffices. However, in the given example, the program aims to handle the ENOSPC (no space left on device) error specifically. The os package provides an *os.PathError as the error implementation in such cases. If you need to access further information about the error, you can cast it.
The statement e, ok := err.(os.PathError) employs type assertion. It verifies if the interface value err holds a os.PathError as its concrete type, and if so, it returns that value. If a different type is present in the interface (other types may also implement the error interface), it simply returns the zero value and false (nil, false in this case).
The above is the detailed content of When and Why Use `err.(*os.PathError)` in Go?. For more information, please follow other related articles on the PHP Chinese website!