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?
It's type assertion. I can't explain it better than the spec.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With