Go中的错误(* os.PathError)是什么? [英] What is err.(*os.PathError) in Go?

查看:104
本文介绍了Go中的错误(* os.PathError)是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读时: http://golang.org/doc/effective_go.html#errors

在这种情况下,我发现了这样一行: err。(* os.PathError)

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 }

究竟是 err。(* os.PathError)在Go?

推荐答案

os.Create 返回一个错误作为第二个返回值。错误本身是一个接口 类型错误接口{Error()string} 。任何恰好具有 Error 方法的数据类型都将实现该接口并可以分配。

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.

在大多数情况下,只是打印错误就足够了,但在本例中,您希望显式地处理 ENOSPC (设备上没有剩余空间)。在这种情况下, os 包会返回一个 * os.PathError 作为错误实现,并且如果您想访问有关错误,即 Error()字符串方法中的所有内容,您必须将其转换。

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.

语句 e,ok:= err。(* os.PathError)类型断言。它将检查接口值 err 是否包含 * os.PathError 作为具体类型,并将返回该值。如果另一个类型存储在接口中(可能有其他类型实现错误接口),那么它只会返回零值和false,即 nil,false

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.

这篇关于Go中的错误(* os.PathError)是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆