英文:
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.ExitError
。ok
让你知道它是还是不是。最后,exiterr
是err
,但是“转换”为*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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论