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

后端 未结 2 605
有刺的猬
有刺的猬 2020-12-31 14:04

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;         


        
相关标签:
2条回答
  • 2020-12-31 14:23

    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.

    0 讨论(0)
  • 2020-12-31 14:33

    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.

    0 讨论(0)
提交回复
热议问题