问题描述
以下问题有多种答案/技巧:
There are multiple answers/techniques to the below question:
- 如何为 golang 结构体设置默认值?
- 如何在 golang 中初始化结构
我有几个答案,但需要进一步讨论.
I have a couple of answers but further discussion is required.
推荐答案
强制方法获取结构体(构造函数方式).
Force a method to get the struct (the constructor way).
NewMyType()
NewMyType()
这可以通过简单地使类型本身不导出来完成.您可以导出函数 NewSomething 甚至字段 Text 和 DefaultText,但不要导出结构类型的东西.
This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.
另一种为您自己的模块定制它的方法是使用 配置结构以设置默认值(链接中的选项 5).虽然不是一个好方法.
Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.
这篇关于如何在 Go 结构体中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!