Golang之函数选项模式
生活随笔
收集整理的這篇文章主要介紹了
Golang之函数选项模式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
僅做記錄
/*Functional Options函數(shù)選項(xiàng)模式(簡稱FOP模式)既保持了兼容性,而且每增加1個新屬性只需要1個With函數(shù)即可,大大減少了修改代碼的風(fēng)險
*/
package mainimport "fmt"/*Functional Options函數(shù)選項(xiàng)模式(簡稱FOP模式)既保持了兼容性,而且每增加1個新屬性只需要1個With函數(shù)即可,大大減少了修改代碼的風(fēng)險
*/type Student struct {Name stringAge intSex string
}//定義類型函數(shù)
type StudentOption func(*Student)//創(chuàng)建帶有age的構(gòu)造函數(shù)
func WithAge(age int) StudentOption {return func(s *Student) {s.Age = age}
}func WithSex(sex string) StudentOption {return func(s *Student) {s.Sex = sex}
}//創(chuàng)建帶有默認(rèn)值的構(gòu)造函數(shù)
func NewStudent(name string, options ...StudentOption) *Student {student := &Student{Name: name}for _, o := range options {o(student)}return student
}func main() {student := NewStudent("fourier", WithAge(6), WithSex("男"))fmt.Println(student)teacher := NewTeacher("fourier", WithTeacherAge(20), WithGender("男"))fmt.Println(teacher)
}type Teacher struct {Name stringAge intGender string
}type TeacherOptions func(*Teacher)func WithTeacherAge(age int) TeacherOptions {return func(teacher *Teacher) {teacher.Age = age}
}func WithGender(gender string) TeacherOptions {return func(teacher *Teacher) {teacher.Gender = gender}
}func NewTeacher(name string, options ...TeacherOptions) *Teacher {teacher := &Teacher{Name: name}for _, option := range options {option(teacher)}return teacher
}
總結(jié)
以上是生活随笔為你收集整理的Golang之函数选项模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如果没准备这些面试题,找工作还是缓一缓吧
- 下一篇: 2021 元宇宙研究报告!