Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the usage of reflection be avoided in Go?

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?

like image 964
linirod Avatar asked Dec 20 '15 20:12

linirod


People also ask

Why not use reflect in Golang?

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.

Should we use reflect in Golang?

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.

Does Go support reflection?

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.

Is reflection slow in Golang?

Reflection in Go is slow because it needs to do quite a few allocations.


2 Answers

There are a few problem domains where reflection makes it easier to write reusable libraries:

  • marshalling/unmarshalling, plenty of examples in the standard library, e.g. encoding/json, encoding/xml
  • formatting, e.g. text/template, html/template, fmt.Printf.

However there is a price you pay for using reflection:

  • compile time errors become runtime errors (e.g. fmt.Printf("%d", stringVariable))
  • performance becomes worse

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.

like image 171
kostya Avatar answered Oct 23 '22 06:10

kostya


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.

like image 33
Volker Avatar answered Oct 23 '22 04:10

Volker