4 ms·
Two valid use cases I've found for interface{}: Handling large arbitrary JSON objects where I need to operate on their keys but don't need to work with their v
by ben_jones 7y ago
Two valid use cases I've found for interface{}:
Handling large arbitrary JSON objects where I need to operate on their keys but don't need to work with their values by unmarshaling to map[string]interface{}. The alternative would likely be code generation of struct definitions with JSON bindings, which is likely preferable if you already have code generation in your project, but can be an overhead in smaller ones.
It can also be used to create your own syntactic wrappers around API's which consume interface{} such as encoding/json and database/sql:
Unmarshal(r *http.Response, dst interface{}) ([]byte, error)
and
BulkInsert(tableName string, columns []string, values [][]interface{}) (time.Duration, error)
- deleted 7y ago[deleted]
- cle 7y agoHandling JSON is the one place where I’ve used interface{} and not felt dirty. Sometimes you really do need to model “anything” or “whatever”, especially when passing around arbitrary data without making assumptions about its schema.
- RSZC 7y agoI use it for shutdown channels. It doesn't matter what you're putting in the channel if you're never putting anything in the channel
- zeeboo 7y agoUsing chan struct{} is more efficient, and guarantees there is nothing being put into the channel. That's why you see it used on the Context type's Done method, for example. https://golang.org/pkg/context/#Context https://golang.org/pkg/context/#Context
- stevelosh 7y ago> Handling large arbitrary JSON objects where I need to operate on their keys but don't need to work with their values by unmarshaling to map[string]interface{}. If you just need the keys, you should unmarshal to `map[string]json.RawMessage` to avoid the overhead of parsing the values into objects only to throw them away without ever using them.