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?

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.

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.