猿问

如何在 Go 结构中设置默认值

以下问题有多种答案/技术:

  1. 如何为 golang 结构设置默认值?

  2. 如何在golang中初始化结构

我有几个答案,但需要进一步讨论。


蝴蝶刀刀
浏览 305回答 3
3回答

哈士奇WWW

一种可能的想法是编写单独的构造函数//Something is the structure we work withtype Something struct {     Text string      DefaultText string } // NewSomething create new instance of Somethingfunc NewSomething(text string) Something {   something := Something{}   something.Text = text   something.DefaultText = "default text"   return something}

吃鸡游戏

强制方法获取结构(构造方法)。从这篇文章:一个好的设计是让你的类型不被导出,但是提供一个导出的构造函数NewMyType(),你可以在其中正确地初始化你的结构/类型。还要返回一个接口类型而不是具体类型,并且该接口应该包含其他人想要对您的值执行的所有操作。当然,您的具体类型必须实现该接口。这可以通过简单地使类型本身不导出来完成。您可以导出函数 NewSomething 甚至字段 Text 和 DefaultText,但不要导出结构类型的东西。为您自己的模块自定义它的另一种方法是使用Config 结构来设置默认值(链接中的选项 5)。不过也不是什么好办法。

蛊毒传说

Victor Zamanian 回答的选项 1 的一个问题是,如果未导出类型,则包的用户无法将其声明为函数参数等的类型。解决此问题的一种方法是导出接口而不是结构例如package candidate// Exporting interface instead of structtype Candidate interface {}// Struct is not exportedtype candidate struct {    Name string    Votes uint32 // Defaults to 0}// We are forced to call the constructor to get an instance of candidatefunc New(name string) Candidate {    return candidate{name, 0}  // enforce the default value here}这让我们可以使用导出的 Candidate 接口声明函数参数类型。我可以从这个解决方案中看到的唯一缺点是我们所有的方法都需要在接口定义中声明,但你可能会争辩说这无论如何都是好的做法。
随时随地看视频慕课网APP

相关分类

Go
我要回答