Search code examples
reflectiongointerface

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?


Solution

  • 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.