如何在Go结构中设置默认值 [英] How to set default values in Go structs

查看:283
本文介绍了如何在Go结构中设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are multiple answers/techniques to the below question:


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

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

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

I have a couple of answers but further discussion is required.

推荐答案


  1. 强制使用一种方法来获取结构(构造方法)。

  1. Force a method to get the struct (the constructor way).

来自此帖子


一个好的设计是使您的类型不导出,但是提供一个导出的构造函数,例如 NewMyType(),在其中您可以正确地初始化您的struct / type。还返回接口类型而不是具体类型,并且该接口应包含其他人希望对您的值进行的操作。当然,您的具体类型必须实现该接口。

A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.

这可以通过简单地使类型本身不导出来完成。您可以导出函数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屋!

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