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?
Disadvantages of reflectAffects code readability. Unable to detect errors during code compilation. As a statically typed language, the Go compiler will pre-check some types of error during compilation. When type is not explicitly defined in interface , the server is at risk of panicking after running the code.
Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose. Reflection is often termed as a method of metaprogramming.
Reflection gives you the ability to examine types at runtime. It also allows you to examine, modify, and create variables, functions, and structs at runtime. Reflection in Go is built around three concepts: Types, Kinds, and Values.
Reflection in Go is slow because it needs to do quite a few allocations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With