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)
}
posted @   沧海一声笑rush  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
历史上的今天:
2022-01-11 RPC 入门(一)
点击右上角即可分享
微信分享提示