Golang中最灵活的功能签名 [英] Most flexible function signature in golang

查看:52
本文介绍了Golang中最灵活的功能签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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())

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:

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

看看有效的Go的以下部分: http://golang.org/doc/effective_go.html#data

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

对于极其复杂的情况,请使用配置结构(选项3,位于 http://joneisen.tumblr.com/post/53695478114/golang-and-default-values )有时也会与 NewConfigStruct()一起使用默认值初始化配置实例.用户生成一个默认实例,设置所需的字段,然后将其传递给他们正在创建的实际结构的 New 函数.

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.

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

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