Go函式式選項模式
阿新 • • 發佈:2022-04-18
一.引入
在編寫程式碼時,當我們通過一個結果體構造一個新的物件時,往往會像下邊這樣,但如果結構體中有很多的欄位,而且在構造新物件時只需要修改很少的欄位,其它欄位都使用預設值,用下邊這種方式就會顯得很笨重,這裡我們就可以引入函式式選項模式的概念.
type student struct {
name string
age int
class string
}
func main() {
stu := student{"Alex", 20, "math"}
stu2 := student{
name: "alex",
age: 40,
}
}
Functional options 是一種模式,在該模式中,你可以宣告一個不透明的
Option
型別,該型別在某些內部結構中記錄資訊。你接受這些可變數量的選項,並根據內部結構上的選項記錄的完整資訊進行操作。將此模式用於建構函式和其他公共 API 中的可選引數,你預計這些引數需要擴充套件,尤其是在這些函式上已經有三個或更多引數的情況下。
二.示例
type student struct { name string age int class string } type stuOption func(*student) func withAge(a int) stuOption { // 設定年齡 return func(s *student) { s.age = a } } func withClass(c string) stuOption { // 設定課程 return func(s *student) { s.class = c } } func newStudent(name string, options ...stuOption) *student { stu := &student{name: name, age: 20, class: "math"} // 年齡預設為20,課程預設為math for _, o := range options { o(stu) } return stu } func main() { s := newStudent("Lilith", withAge(10)) s2 := newStudent("Ulrica", withAge(100), withClass("chinese")) fmt.Println(*s) // {Lilith 10 math} fmt.Println(*s2) // {Ulrica 100 chinese} }
上邊程式碼中我們通過with*的形式給結構體變數賦值,在呼叫newStudent函式時,如果沒有指定除name外的變數值就使用預設值,如s未指定class的值,結果class為預設值math,這樣就可以更加靈活的對結構體進行修改,新增結構體變數時只需新增對應的with*函式即可.