Go 中的构造函数 [英] Constructors in Go

查看:28
本文介绍了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:

  1. 将结构的零值设为合理的默认值.(虽然对于大多数来自传统"oop 的人来说这看起来很奇怪,但它通常有效并且非常方便).
  2. 提供一个函数 func New() YourTyp 或者如果你的包函数中有几个这样的类型 func NewYourType1() YourType1 等等.
  1. 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).
  2. Provide a function func New() YourTyp or if you have several such types in your package functions func NewYourType1() YourType1 and so on.

记录您的类型的零值是否可用(在这种情况下,它必须由 New... 函数之一设置.(对于传统主义者"oops:不阅读文档的人将无法正确使用您的类型,即使他无法创建处于未定义状态的对象.)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆