英文:
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/json
,encoding/xml
- 格式化,例如
text/template
,html/template
,fmt.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论