一般在调用函数时,遇到可选参数是非常广泛的。
在Go中可以使用函数闭包实现可选参数功能,最近在学习一些go写的包,看过源码,也都是采用这种方式,值得学习
- package mainimport ( "fmt")type Person struct { name string age int gender string}// 界说options参数的范例,这里界说为一个函数type option func(*Person)// 通过withage函数去界说结构体的属性值func withage(age int) option { return func(p *Person) { p.age = age }}func NewPerson(name string, gender string, opts ...option) *Person { p := &Person{ name: name, gender: gender, age: 10, // 默认设置age属性为10 } for _, opt := range opts { opt(p) } return p}func main() { p := NewPerson("xiaoming", "男", withage(11)) // withage(11) 会将结构体对象的age设置为11,返回的函数对象也符合option的界说 fmt.Println(p)}
复制代码
来源:https://blog.csdn.net/xiaohuyi/article/details/111995107
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |