Go /可选参数中有多个构造函数?

时间:2019-05-17 00:44:19

标签: go constructor

我想知道是否有一种方法可以像在Java中那样在Go中实现多个构造函数(具有相同的函数名)。另一个选择可能是只有一个带有可选参数的构造函数,但是我不确定如何精确地做到这一点。

This seems similar to what I was trying to do

function drop()
    {
        echo form_open('forms/get_val', 'class="email" id="myform"'); //replace it to your controller name and function name
        $options = array(
                'small'         => 'Small Shirt',
                'med'           => 'Medium Shirt',
                'large'         => 'Large Shirt',
                'xlarge'        => 'Extra Large Shirt',
        ); //setting up an option for dropdown

        $shirts_on_sale = array('small', 'large'); //put this as a 3rd param to set dropdown selected as listed.
        echo form_dropdown('shirts', $options); //you can add it here the $shirt_on_sale

        echo form_submit('mysubmit', 'Submit Post!'); //submit button
    }

function get_val() //success page
{
    echo $this->input->post('shirts'); //display the selected value.
}

第一个构造函数使用一个参数type Query struct { TagsQuery string PageQuery string } // First Constructor func NewQuery(TagsQuery string) Query { return Query{ TagsQuery: TagsQuery, PageQuery: "0", // default to first page } } // Second Constructor func NewQuery(TagsQuery string, PageQuery string) Query { return Query{ TagsQuery: TagsQuery, PageQuery: PageQuery, } } ,并且默认将TagsQuery设置为PageQuery。第二个构造函数采用两个参数:0TagsQuery

1 个答案:

答案 0 :(得分:5)

戴夫·切尼(Dave Cheney)通过功能选项为该问题提供了解决方案:

https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis

因此,您将接受许多可以修改正在创建的结构的函数。在您的情况下,您可以仅对可选的PageQuery字段执行此操作,尽管它是一个...参数,但将来可能会接受更多内容:

type Query struct {
    TagsQuery string
    PageQuery string
}

// First Constructor
func NewQuery(TagsQuery string, options ...Option) Query {
    query := Query{
        TagsQuery: TagsQuery,
        PageQuery: "0", // default to first page
    }
    // Apply options if there are any, can overwrite default
    for _, option := range options {
        query = option(query)
    }
    return query
}

// Option definition
type Option func(Query) Query

// Function to create Option func to set pageQuery
func WithPageQuery(pageQuery string) Option {
    return func(query Query) Query {
        query.PageQuery = pageQuery
        return query
    }
}

然后调用它:

NewQuery("tags query only")
NewQuery("tags query", WithPageQuery("page query"))