Go中的构造函数 [英] Constructors in Go
问题描述
我有一个结构,我希望使用一些合理的默认值对其进行初始化.
I have a struct and I would like it to be initialised with some sensible default values.
通常,这里要做的是使用构造函数,但是由于go在传统意义上并不是真正的OOP,所以它们不是真正的对象,并且没有构造函数.
Typically, the thing to do here is to use a constructor but since go isn't really OOP in the traditional sense these aren't true objects and it has no constructors.
我注意到了init方法,但这是在程序包级别的.还有其他类似的东西可以在结构级别使用吗?
I have noticed the init method but that is at the package level. Is there something else similar that can be used at the struct level?
如果不是,那么Go中这种事情的公认最佳实践是什么?
If not what is the accepted best practice for this type of thing in Go?
推荐答案
实际上有两种公认的最佳实践:
There are actually two accepted best practices:
- 将结构的零值设为明智的默认值. (虽然这对于大多数来自传统"操作的人来说很奇怪,但它通常可以工作并且非常方便.)
- 提供一个函数
func New() YourTyp
,或者如果您的包装函数func NewYourType1() YourType1
中包含多个此类,则依次类推.
- Make the zero value of your struct a sensible default. (While this looks strange to most people coming from "traditional" oop it often works and is really convenient).
- Provide a function
func New() YourTyp
or if you have several such types in your package functionsfunc NewYourType1() YourType1
and so on.
文档,如果您的类型的零值不可用(在这种情况下,必须由New...
函数之一设置.)(对于传统主义者"哎呀:那些不阅读文档的人会获胜即使他无法以未定义状态创建对象,也无法正确使用您的类型.)
Document if a zero value of your type is usable or not (in which case it has to be set up by one of the New...
functions. (For the "traditionalist" oops: Someone who does not read the documentation won't be able to use your types properly, even if he cannot create objects in undefined states.)
这篇关于Go中的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!