【发布时间】:2013-11-22 17:13:27
【问题描述】:
我发现自己使用以下模式来获取 Go 结构构造函数中具有默认值的可选参数:
package main
import (
"fmt"
)
type Object struct {
Type int
Name string
}
func NewObject(obj *Object) *Object {
if obj == nil {
obj = &Object{}
}
// Type has a default of 1
if obj.Type == 0 {
obj.Type = 1
}
return obj
}
func main() {
// create object with Name="foo" and Type=1
obj1 := NewObject(&Object{Name: "foo"})
fmt.Println(obj1)
// create object with Name="" and Type=1
obj2 := NewObject(nil)
fmt.Println(obj2)
// create object with Name="bar" and Type=2
obj3 := NewObject(&Object{Type: 2, Name: "foo"})
fmt.Println(obj3)
}
有没有更好的方法来允许带有默认值的可选参数?
【问题讨论】:
-
怎么了:play.golang.org/p/DYw5pWzRQC?更少的代码,更好的理解,更通用的......上面看起来像是一个等待问题的解决方案......
-
目前,我正在使用这种模式在测试中创建夹具。恕我直言,明确分配默认值不会使这些测试更易于理解或更具可读性。
标签: constructor go default