5

Go Newb here -- I've encountered the following bit of Go code that I didn't write

if tc, ok := tng.(ThingClasser); ok {
    //... do some stuff ...
}

I won't understand the semantics of tng.(ThingClasser).

In some ways this looks like a method call -- i.e. there are two variables (ec, ok) sitting there ready to accept multiple return values.

However, tng.(ThingClasser) itself looks like its a property access, not a method call.

However however, the parens around ThingClasser are a wrinkle I've never seen before. Also, if it matters, the ThingClasser symbol is defined elsewhere in this project as an interface, so I think maybe this is some syntactic sugar around an does this implement an interface -- but then the two return values confused me.

Googling hasn't turned up anything concrete, but this is one of those hard things to google for.

Does anyone here know what this call/syntax is in GoLang, and possible point me at the relevant manual pages so I can RTFM?

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
  • 2
    The [Go language spec](https://golang.org/ref/spec) is relatively simple. That's the best place to check for these things. Searching for `.(` finds the "Type Assertion" specification quickly. – JimB Oct 10 '17 at 18:36

1 Answers1

3

It's a type assertion. The returned values are 1) the object, converted to the given type; and 2) a boolean indicating if the conversion was successful. ThingClasser is the type being converted to. Documentation can be found here: https://golang.org/ref/spec#Type_assertions

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • 2
    As a side note, the Go spec is worth reading. Unlike most modern languages, it's short - really short. 1/5 the size of the C# spec, and 1/10 the size of the Java spec. Thanks to Go's simplicity, you can read the entire raw language spec in a couple hours and gain a lot from it. – Adrian Oct 10 '17 at 18:36