dsfdsf46465
2013-08-20 16:34
浏览 431
已采纳

Go中的错误(* os.PathError)是什么?

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?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doude4924 2013-08-20 17:09
    已采纳

    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.

    已采纳该答案
    打赏 评论
  • dousui4577 2013-08-20 16:43

    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.

    打赏 评论

相关推荐 更多相似问题