一般在调用函数时,遇到可选参数是非常普遍的。
在Go中可以利用函数闭包实现可选参数功能,最近在学习一些go写的包,看过源码,也都是采用这种方式,值得学习
package main
import (
"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)
}