dozc1071
dozc1071
2019-05-17 00:44

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

  • constructor

I was wondering if there was a way to implement multiple constructors (with the same function name) in Go, just like you can do in Java. Another option could be to only have one constructor with an optional parameter, but I am not sure how to do that exactly.

This seems similar to what I was trying to do

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,
    }
}

The first constructor takes one argument TagsQuery and defaults PageQuery to 0. The second constructor takes two arguments: TagsQuery and PageQuery.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐