问题描述

我的代码中包含对象初始化器,该初始化器显式初始化对象的每个字段.但就我而言,大多数参数都有合理的默认值,我想使用它们.

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.

 __ init __ 
__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('mondatory', bar=Bar())

Go中没有默认值的参数,也没有关键字参数或函数重载.因此,很难编写灵活的初始化代码(通常我不太在意此类代码的性能).我想找到最惯用的方式在Go中编写此类代码.也许运行时类型反射和映射的某种组合可以完成任务,您认为呢?

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?

推荐答案

由于Go中新分配的内存始终为零,因此惯用的方法是通过以下方式显式地利用这一事实:

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

  • 将结构设计为具有合理的零值
  • 使用复合文字

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

 NewConfigStruct() New 
NewConfigStruct()New

这篇关于Golang中最灵活的功能签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!