Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

go

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?

like image 524
OscarRyz Avatar asked May 02 '12 13:05

OscarRyz


2 Answers

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

like image 116
Mostafa Avatar answered Oct 30 '22 11:10

Mostafa


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.

like image 33
425nesp Avatar answered Oct 30 '22 11:10

425nesp