【发布时间】:2019-10-04 07:14:03
【问题描述】:
我想知道是否有一种方法可以在 Go 中实现多个构造函数(具有相同的函数名称),就像在 Java 中一样。另一种选择可能是只有一个带有可选参数的构造函数,但我不确定该怎么做。
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,
}
}
第一个构造函数接受一个参数TagsQuery,默认PageQuery 为0。第二个构造函数有两个参数:TagsQuery 和 PageQuery。
【问题讨论】:
-
Go 语言设计者明确选择不包含此功能,无论好坏。
NewQuery和NewQueryWithPage怎么样? -
Optional Parameters?的可能重复
标签: go constructor