go 语言的 option 模式 (函数式选项模式)
该模式要解决什么样的问题?
该模式主要解决,如何实现一个函数的某几个入参的可选输入。
例如: 学生信息登记系统。同年级的学生,一般年龄和年级,都是固定的,仅有名字是可变的。因此可将名字作为必选入参,年龄和年级作为可选入参
如果使用 python
实现,非常简单:
复制def new_student(name,age=8,grade=1):
print(f"学生{name};年龄{age};年级 {grade}")
如果使用 go 语言,怎么实现呢?可能就有点复杂了
使用go语言的option模式实现简单的可选入参
type Student struct {
Name string
Age int
Grade int
}
type FuncStudentOption func(*Student)
func NewStudent(name string, opts ...FuncStudentOption) *Student {
student := &Student{
Name: name,
Age: 8,
Grade: 1,
}
for _, opt := range opts {
opt(student)
}
return student
}
//使用闭包的方式,修改 student 结构体内的值
func witchAge(age int) FuncStudentOption {
return func(student *Student) {
student.Age = age
}
}
func witchGrade(grade int) FuncStudentOption {
return func(student *Student) {
student.Grade = grade
}
}
func main() {
s := NewStudent("小明")
fmt.Println(s)
s2 := NewStudent("小刘", witchAge(20), witchGrade(8))
fmt.Println(s2)
}
高阶实现
如上的实现方法,有个问题,就是 student
结构体内的属性,如果都是 public
的,相当于都可以被外界访问,别人可以随意更改,如何把这些封装起来,不让外界访问呢?
type Student struct {
name string
age int
grade int
}
// 接口其实就是一组方法的标识符
type StudentOption interface {
apply(*Student)
}
// 这个其实就是个入参
type ageOption int
func (a ageOption) apply(s *Student) {
s.age = int(a)
}
func WithAge(age int) StudentOption {
return ageOption(age)
}
func NewStudent(name string, opts ...StudentOption) *Student {
s := &Student{
name: name,
age: 8,
grade: 1,
}
for _, opt := range opts {
opt.apply(s)
}
return s
}
func main() {
s1 := NewStudent("小明")
fmt.Println(s1)
s2 := NewStudent("小明", WithAge(12))
fmt.Println(s2)
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
2022-01-11 RPC 入门(一)