,我发现自己使用下面的模式作为一种可选的参数,以获得可选参数与围棋结构构造函数的默认值:在围棋结构构造默认
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)
}
是否有允许可选的更好的方法参数与默认?
有什么问题:http://play.golang.org/p/DYw5pWzRQC? 更少的代码,更好的理解,更通用... 上面看起来像一个等待问题的解决方案... – metakeule
目前,我正在使用这种模式来创建测试中的灯具。恕我直言,明确分配默认值不会使这些测试更易于理解或更具可读性。 –