在Go语言中,应该避免使用反射吗?

huangapple go评论90阅读模式
英文:

Should the usage of reflection be avoided in Go?

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我对Go语言和reflection概念都不熟悉,但是在Go中是否应该避免使用reflect包?是否存在无法避免使用reflect的情况?

英文:

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?

答案1

得分: 13

有一些问题领域,使用反射可以更容易编写可重用的库:

  • 编组/解组,标准库中有很多例子,例如encoding/jsonencoding/xml
  • 格式化,例如text/templatehtml/templatefmt.Printf

然而,使用反射会付出一定的代价:

  • 编译时错误变成了运行时错误(例如fmt.Printf("%d", stringVariable)
  • 性能变差

很多时候,存在不需要使用反射的替代解决方案,例如代码生成,这种方法被编组库(如protobuf或thrift)使用。

我同意@volker的观点,只有在你知道使用反射能简化已有代码并且了解所有缺点时,才应该使用反射。

英文:

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.

答案2

得分: 8

你应该避免使用反射。

一些包(例如fmt)在没有反射的情况下无法实现,因为你无法对所有现有和即将出现的类型进行类型切换。

如果你是Go的新手:请远离反射。

英文:

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.

huangapple
  • 本文由 发表于 2015年12月21日 04:53:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/34385735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定