这个 “err.(*exec.ExitError)” 在 Go 代码中是什么东西?

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

What is this "err.(*exec.ExitError)" thing in Go code?

问题

在这个答案中,err.(*exec.ExitError) 是什么?它是如何工作的?

英文:

For instance, in this answer:

https://stackoverflow.com/a/10385867/20654

...
if exiterr, ok := err.(*exec.ExitError); ok {
...

What is that err.(*exec.ExitError) called? How does it work?

答案1

得分: 20

这是类型断言。我无法比规范更好地解释它。

英文:

It's type assertion. I can't explain it better than the spec.

答案2

得分: 6

这是一种类型断言。那个if语句正在检查err是否也是一个*exec.ExitErrorok让你知道它是还是不是。最后,exiterrerr,但是“转换”为*exec.ExitError。这只适用于interface类型。

如果你对底层类型非常确定,也可以省略ok。但是,如果省略ok,结果证明你错了,那么会引发panic

// 通过检查第二个值在运行时找出是否为真
exitErr, isExitError := err.(*exec.ExitError)

// 如果err不是*exec.ExitError,将引发panic
exitErr := err.(*exec.ExitError)

顺便说一下,ok不是语法的一部分。它只是一个布尔值,你可以随意命名它。

英文:

It's a type assertion. That if statement is checking if err is also a *exec.ExitError. The ok let's you know whether it was or wasn't. Finally, exiterr is err, but "converted" to *exec.ExitError. This only works with interface types.

You can also omit the ok if you're 100000 percent sure of the underlying type. But, if you omit ok and it turns out you were wrong, then you'll get a panic.

// find out at runtime if this is true by checking second value
exitErr, isExitError := err.(*exec.ExitError)

// will panic if err is not *exec.ExitError
exitErr := err.(*exec.ExitError)

The ok isn't part of the syntax, by the way. It's just a boolean and you can name it whatever you want.

huangapple
  • 本文由 发表于 2012年5月2日 21:56:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/10415240.html
匿名

发表评论

匿名网友

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

确定