英文:
How to provide optional parameters in Go?
问题
我来自Node.js背景,那里的典型模式是使用一个接受选项对象的函数,即一个你可以设置可选参数属性的对象,例如:
foo({
bar: 23,
baz: 42
});
这是JavaScript中"等效"于可选和命名参数的方式。
现在我了解到Go语言中没有可选参数,除了可变参数,但它们缺乏命名参数的可读性。所以通常的模式似乎是传递一个结构体。
然而,结构体不能定义默认值,所以我需要一个函数来设置结构体。
所以我最终得到:
- 调用一个创建结构体并填充默认值的函数。
- 覆盖我想要更改的值。
- 调用我实际想要调用的函数并传递结构体。
与JavaScript的解决方案相比,这相当复杂和冗长。
这实际上是在Go语言中处理可选和命名参数的惯用方式吗?还是有更简单的版本?
英文:
I'm coming from a Node.js background, and there a typical pattern is to have a function which takes an options object, i.e. an object where you set properties for optional parameters, such as:
foo({
bar: 23,
baz: 42
});
This is JavaScript's "equivalent" to optional and named parameters.
Now I have learnt that there are no optional parameters in Go, except variadic parameters, but they lack the readability of named parameters. So the usual pattern seems to be to hand over a struct.
OTOH a struct can not be defined with default values, so I need a function to set up the struct.
So I end up with:
- Call a function that creates the struct and then fills it with default values.
- Overwrite the values I would like to change.
- Call the function I actually want to call and hand over the struct.
That's quite complicated and lengthy compared to JavaScript's solution.
Is this actually the idiomatic way of dealing with optional and named parameters in Go, or is there a simpler version?
答案1
得分: 4
有没有办法利用零值?所有数据类型都会被初始化为零值,这是一种默认逻辑。
选项对象是一个相当常见的习语。etcd客户端库有一些类似以下示例的选项(SetOptions、GetOptions、DeleteOptions)。
type MyOptions struct {
Field1 int // int的零值(默认值)是0
Field2 string // string的零值(默认值)是""
}
func DoAction(arg1, arg2 string, options *MyOptions){
var defaultValue1 int = 30 // 一些合理的默认值
var defaultValue2 string = "west" // 一些合理的默认值
if options != nil {
defaultValue1 = options.Field1 // 使用我们的值进行覆盖
defaultValue2 = options.Field2
}
doStuffWithValues
}
一个相关的问题(也非常符合Go的思维方式)是,你是否需要这种复杂性?灵活性很好,但标准库中的大多数东西都只尝试处理一次默认的信息/逻辑,以避免这种情况。
英文:
Is there any way that you can take advantage of zero values? All data types get initialized to a zero value, so that is a form of default logic.
An options object is a pretty common idiom. The etcd client library has some examples (SetOptions,GetOptions,DeleteOptions) similar to the following.
<!-- language: lang-go -->
type MyOptions struct {
Field1 int // zero value (default) of int is 0
Field2 string // zero value (default) of string is ""
}
func DoAction(arg1, arg2 string, options *MyOptions){
var defaultValue1 int = 30 // some reasonable default
var defaultValue2 string = "west" // some reasonable default
if options != nil {
defaultValue1 = options.Field1 // override with our values
defaultValue2 = options.Field2
}
doStuffWithValues
An relevant question (and very much in the mindset of Go) would be, do you need this kind of complexity? The flexibility is nice, but most things in the standard library try to only deal with 1 default piece of info/logic at a time to avoid this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论