|
|
|
|
|
by Firstmate
4419 days ago
|
|
New to Go still, what kind of caution should one take when using interface{} to store data in structs? It seems to be a catch-all sort of type, I've read how cluttered some code can get when using it (I think it was an HN post related to math in Go, and type-checking against an interface{} type). Thanks |
|
The key is that an `interface{}` is an interface with exactly 0 methods. Since all types in Go have at least 0 methods, any type satisfies `interface{}`. Resorting to using an `interface{}` type is akin to dynamic typing. All of your type errors get pushed to runtime and you lose any performance benefits you might get from the compiler knowing the type of your data.
Russ Cox goes into great detail on the representation of interface values.[1]
I wrote a blog post a while back on conveniently writing parametric functions in Go using reflection.[2] (Here, "convenience" is a relative term.)
[1] - http://research.swtch.com/interfaces
[2] - http://blog.burntsushi.net/type-parametric-functions-golang