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

查看:40
本文介绍了如何在 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(),你可以在其中正确地初始化你的结构/类型.还要返回一个接口类型而不是具体类型,并且该接口应该包含其他人想要对您的值执行的所有操作.当然,您的具体类型必须实现该接口.

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天全站免登陆