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

When I read: http://golang.org/doc/effective_go.html#errors

I found a line like this: 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 is err.(*os.PathError) in Go?

+6
source share
2 answers

os.Create returns an error as the second return value. The error itself is an interface type error interface { Error() string } . Any data type that has the Error method implements this interface and can be assigned.

In most cases, just printing an error is enough, but in this example you want to explicitly handle ENOSPC (without a space on the device). The os package returns *os.PathError as the implementation of the error in this case, and if you want to get additional information about the error, i.e. Anything next to the Error() string method, you will have to convert it.

The statement e, ok := err.(*os.PathError) is a type statement. It will check if the err *os.PathError interface value is as a specific type and return it. If another type was stored in the interface (there may be other types that implement the Error interface), then it will simply return zero and false, i.e. nil, false in this case.

+15
source

From docs , this is a statement like:

For an expression of type x interface and type T primary expression

  x.(T) 

states that x is not nil and that the value stored in x is of type T. The notation x. (T) is called a type statement.

+7
source

Source: https://habr.com/ru/post/952128/


All Articles