18

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?

Steffi Keran Rani J
  • 3,667
  • 4
  • 34
  • 56
OscarRyz
  • 196,001
  • 113
  • 385
  • 569

2 Answers2

20

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

Mostafa
  • 26,886
  • 10
  • 57
  • 52
  • Thanks. In that sense is it similar to a cast? – OscarRyz May 02 '12 at 15:45
  • 2
    Well, only "similar." Casting is called [conversion](http://golang.org/ref/spec#Conversions) in Go. It may be right to say that conversion happens at compile-time, and assertion at runtime. – Mostafa May 02 '12 at 16:38
6

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.

425nesp
  • 6,936
  • 9
  • 50
  • 61