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

huangapple go评论82阅读模式
英文:

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

问题

err.(*os.PathError) 是 Go 语言中的类型断言语法。它用于将 err 转换为 *os.PathError 类型。类型断言用于判断一个接口值是否实现了特定的接口类型,并将其转换为该类型。在这个上下文中,err.(*os.PathError) 的作用是判断 err 是否是 *os.PathError 类型的错误,并将其转换为 *os.PathError 类型的变量 e。这样可以通过 e 来访问 *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?

答案1

得分: 24

os.Create作为第二个返回值返回一个错误。这个错误本身是一个接口 type error interface { Error() string }。任何具有Error方法的数据类型都将实现该接口,并且可以被赋值。

在大多数情况下,只需打印错误就足够了,但在这个例子中,您希望显式处理ENOSPC(设备上没有剩余空间)错误。在这种情况下,os包将返回一个*os.PathError作为错误实现,如果您想访问有关错误的其他信息,即除了Error() string方法之外的所有内容,您需要进行转换。

语句e, ok := err.(*os.PathError)是一种类型断言。它将检查接口值err是否包含*os.PathError作为具体类型,并返回它。如果接口中存储了另一种类型(可能还有其他实现error接口的类型),那么它将简单地返回零值和false,即在这种情况下为nil, false

英文:

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.

答案2

得分: 7

根据文档,这是一种类型断言:

> 对于一个接口类型的表达式 x 和一个类型 T,主表达式

 x.(T)

> 断言 x 不是 nil,并且 x 中存储的值是类型 T。x.(T) 的表示法称为类型断言。

英文:

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.

huangapple
  • 本文由 发表于 2013年8月21日 00:34:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/18340411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定