Type Inspection In Go
Recently I have been experimenting with and exploring Golang. Here we briefly look at type inspection in Go from the perspective of a JavaScript user
Since it seems to be the vogue inevitability for JS/Node engineers to dabble in Go, I am inevitably, well, dabbling in Go.
My experience with the language so far has been an extremely pleasant one. In many ways it has been like sipping a surprisingly good cup of espresso that I hadn't tried before. Furthermore, the approach it takes to extending functionality has been incredible; it's composition over inheritance, but built into the language.
typeof in Go
One thing I ran into when using Go for the donation pages server for Charityware was checking to see what type I was dealing with at various points in my program. I'm more used to the rampant type coercion of JavaScript, so I reached for some equivalent of typeof to inspect things. typeof is, of course, a reserved word in JavaScript that you get globally provided. In Go, reflection is its own package and it's not hard to use. To inspect the type of a given
Go is statically typed, just pull in the reflect package and use its TypeOf method:
package main
import (
"fmt"
"reflect"
)
type Foo struct {
a string
b string
}
func main() {
fooInt := 2.10000
fmt.Println("FooInt has type ", reflect.TypeOf(fooInt))
zip := "zip"
fmt.Println("zip has type ", reflect.TypeOf(zip))
compositeType := Foo{"a", "b"}
fmt.Println("Foo has type ", reflect.TypeOf(compositeType))
} There's lots more to reflection and typing in Go, but I won't cover it here. See the in-depth post at the Golang official blog, The Laws of Reflection .