,我發現自己使用下面的模式作爲一種可選的參數,以獲得可選參數與圍棋結構構造函數的默認值:在圍棋結構構造默認
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
目前,我正在使用這種模式來創建測試中的燈具。恕我直言,明確分配默認值不會使這些測試更易於理解或更具可讀性。 –