Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is err.(*os.PathError) in Go?

Tags:

go

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?

like image 510
Sławosz Avatar asked Aug 20 '13 16:08

Sławosz


People also ask

What is err in Golang?

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) } }

How do you generate errors in Golang?

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.


2 Answers

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.

like image 166
tux21b Avatar answered Oct 06 '22 20:10

tux21b


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.

like image 21
Alberto Zaccagni Avatar answered Oct 06 '22 19:10

Alberto Zaccagni