Type Inspection In Go
2 minute read
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.
Related:
- A Guide to the React Ecosystem
- 50% off React in Action Today
- A Conceptual Introduction to React Components
- I'm writing a book about React!
- Testing React Components with Enzyme and Mocha
- Start Simply, Simply Start
- Using Event Emitter in Node.js
- React Native: Quick Start and Including Images
- New NPM Module: Favorites
- Method Chaining in JavaScript
- Npm Modules I can't live without (pt. 2)
- Running Node.js Apps in Production
- Server-Side Rendering with React and React-Router
- Installing iojs and Node.js Together
- Get Functional