作為 Golang 開發人員,遇到的眾多問題之一是試圖將函數的參數設為可選。這是一個非常常見的用例,有一些對象應該使用一些基本的默認設置開箱即用,并且您可能偶爾想要提供一些更詳細的配置。
在python 中,你可以給參數一個默認值,并在調用方法時省略它們。但是在 Golang 中,是無法這么做。
那么怎么解決這個問題呢? 答案就是Options模式。Options模式在Golang中應用十分廣泛,幾乎每個框架中都有他的蹤跡。
- 傳統方式:
package main
import "fmt"
type Person struct {
Name string
Age int
Gender int
Height int
Country string
Address string
}
func NewPerson(name string, age, gender, height int, country, address string) *Person{
return &Person{
Name: name,
Age:age,
Gender:gender,
Height:height,
Country:country,
Address:address,
}
}
func main() {
person := NewPerson("dongxiaojian", 18, 1, 180, "china", "Beijing")
fmt.Printf("%+v\n", person)
}
可以發現,在這種方式中,拓展起來是非常麻煩的,以及設置出默認值十分繁瑣。
-
options模式
package main import "fmt" type Person struct { Name string Age int Gender int Height int Country string City string } type Options func(*Person) func WithPersonProperty (name string, age,gender,height int) Options { return func(p *Person){ p.Name = name p.Age = age p.Gender = gender p.Height = height } } func WithRegional(country, city string) Options { return func(p *Person){ p.Country = country p.City = city } } func NewPerson(opt ...Options) *Person{ p := new(Person) p.Country = "china" p.City = "beijing" for _, o := range opt{ o(p) } return p } func main() { // 默認值方式 person := NewPerson(WithPersonProperty("dongxiaojian", 18, 1, 180)) fmt.Printf("%+v\n", person) // 設置值 person2 := NewPerson(WithPersonProperty("dongxiaojian", 18, 1, 180),WithRegional("china", "hebei")) fmt.Printf("%+v\n", person2) }
下次可以通過
with**
函數進行增加屬性,以及使用默認值。 這樣看起來條理清晰了很多。