Most flexible function signature in golang

huangapple go评论77阅读模式
英文:

Most flexible function signature in golang

问题

我在我的代码中有一个对象初始化器,它明确地初始化了对象的每个字段。但在我的情况下,大多数参数都有合理的默认值,我想使用它们。

在Python中,我通常使用关键字参数或默认值的组合,我的__init__方法包含一些验证逻辑,因此我可以在对象初始化中使用零配置原则。例如:

class Foo:
    """This class designed to show zero configuration principle in action"""
    def __init__(self, mandatory, optional=None, **kwargs):
        self.__field1 = mandatory
        self.__field2 = optional or make_default2()
        if 'bar' in kwargs:
            self.__field3 = kwargs['bar']
        else:
            self.__field3 = make_default3()


f = Foo('mandatory', bar=Bar())

Go语言中没有默认值的参数,也没有关键字参数或函数重载。因此,编写灵活的初始化代码很困难(在这种代码中,我通常不太关心性能)。
我想找到在Go语言中编写这样的代码最惯用的方式。也许一些运行时类型反射和映射的组合可以完成这个任务,你觉得呢?

英文:

I have object initializer in my code, that initializes every field of my object explicitly. But in my case, most of the parameters have sensible defaults and I want to use them.

In Python I usually use combination of keyword arguments or defaults and my __init__ method contains some validation logic so I can use zero configuration principle in object initialization. For example:

class Foo:
    """This class designed to show zero configuration
    principle in action"""
    def __init__(self, mandatory, optional=None, **kwargs):
        self.__field1 = mandatory
        self.__field2 = optional or make_default2()
        if 'bar' in kwargs:
            self.__field3 = kwargs['bar']
        else:
            self.__field3 = make_default3()


f = Foo('mondatory', bar=Bar())

There is no parameters with default values in Go nor keyword parameters or function overloads. Because of that - it is difficult to write flexible initialization code (I don't care much about performance in such code usually).
I want to find most idiomatic way to write such code in Go. Maybe some combination of runtime type reflection and maps will do the job, what do you think?

答案1

得分: 5

由于Go语言中新分配的内存总是被清零,惯用的方式是明确利用这一特点:

  • 设计你的结构体使其具有合理的零值
  • 使用复合字面量

请参考《Effective Go》中的以下部分:
http://golang.org/doc/effective_go.html#data

对于非常复杂的情况,有时也会使用配置结构体(参见http://joneisen.tumblr.com/post/53695478114/golang-and-default-values中的选项3),其中包含一个NewConfigStruct()函数,用于使用默认值初始化配置实例。用户生成一个默认实例,设置他们想要的字段,然后将其传递给正在创建的实际结构体的New函数。

英文:

Because newly-allocated memory in Go is always zeroed, the idiomatic way is to make explicit use of this fact by:

  • designing your structs to have have sane zero values
  • using composite literals

Take a look at the following section of Effective Go:
http://golang.org/doc/effective_go.html#data

For extremely complex cases, a configuration struct (option 3 at http://joneisen.tumblr.com/post/53695478114/golang-and-default-values) is also sometimes used, with a NewConfigStruct() that initializes a configuration instance with defaults. The user generates a default instance, sets the fields they want, then passes it to the New function for the actual struct they are creating.

huangapple
  • 本文由 发表于 2014年4月21日 20:08:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/23197144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定