I'm new to Go
and also new to the concept of reflection
, but should and can the usage of reflect package be avoided in Go
? Is there a scenario where reflect
is unavoidable?
There are a few problem domains where reflection makes it easier to write reusable libraries:
encoding/json
, encoding/xml
text/template
, html/template
, fmt.Printf
.However there is a price you pay for using reflection:
fmt.Printf("%d", stringVariable)
)Very often an alternative solution exists that do not require reflection such as code generation, that is used by marshalling libraries like protobuf or thrift.
I agree with @volker that you should use reflection only when you know that it will simplify already existing code and aware of all downsides.
You should avoid reflection.
Some packages (e.g. fmt) cannot be implemented without reflection as you cannot typeswitch on all existing and upcoming types.
If you are new to Go: Keep away from reflection.