go options 模式
...
函数式选项模式的使用场景有哪些呢:我们一般用来配置一些基础的服务配置,比如MySQL,Redis,Kafka的配置,很多可选参数,可以方便动态灵活的配置想要配置的参数。
https://zhuanlan.zhihu.com/p/436468481
type Option func(*User) func WithAge(age int) Option { return func(u *User) { u.Age = age } } func WithEmail(email string) Option { return func(u *User) { u.Email = email } } func WithPhone(phone string) Option { return func(u *User) { u.Phone = phone } } func WithGender(gender string) Option { return func(u *User) { u.Gender = gender } } func NewUser(id string, name string, options ...func(*User)) (*User, error) { user := User{ ID: id, Name: name, Age: 0, Email: "", Phone: "", Gender: "female", } for _, option := range options { option(&user) } //... return &user, nil } user1, err := NewUser("1", "ada") user2, err := NewUser("2", "bob", WithPhone("123456"), WithGender("male"))
...2
1 package main 2 3 import "fmt" 4 5 type Customer struct { 6 id int 7 name string 8 gender string 9 phone string 10 age int8 11 } 12 13 type Option func(customer *Customer) 14 15 func WithId(id int) Option { 16 return func(customer *Customer) { 17 customer.id = id 18 } 19 } 20 21 func WithGender(gender string) Option { 22 return func(customer *Customer) { 23 customer.gender = gender 24 } 25 } 26 27 func WithName(name string) Option { 28 return func(customer *Customer) { 29 customer.name = name 30 } 31 } 32 33 func WithPhone(phone string) Option { 34 return func(customer *Customer) { 35 customer.phone = phone 36 } 37 } 38 39 func WithAge(age int8) Option { 40 return func(customer *Customer) { 41 customer.age = age 42 } 43 } 44 45 func NewCustomer(options ...Option) Customer { 46 customer := Customer{} 47 for _, option := range options { 48 // 用户自定义的初始化函数 49 option(&customer) 50 } 51 return customer 52 } 53 54 55 func main() { 56 customer := NewCustomer(WithAge(20),WithId(1), WithName("lazyr"), WithGender("man"), WithPhone("192993939393")) 57 fmt.Println(customer) 58 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)