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

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

问题描述

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

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()正确
初始化你的结构/类型。也返回一个接口类型而不是
的具体类型,并且该接口应该包含其他所有需要
来处理您的值的所有内容。当然,您的具体类型必须实现
接口。

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 make 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


  1. 另一种自定义模块的方法是使用配置结构设置默认值(链接中的选项5)不是一个好方法。

  1. 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.

这篇关于如何在golang结构中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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