05-Go实现默认参数

Go实现默认参数

举例1

在 Go中是不支持默认参数的,以前我们在Go中大多是使用以下方式来实现的。

但是这种方式侵入性比较强,如果此时我们需要增加一个参数或其他更多参数,那么需要在原代码基础上做很多的修改。

type ExampleClient struct {
	Name string
	Job int
}

func NewExampleClient(name, job string) ExampleClient {
	if name == "" {
		name = "default"
	}
	
	if job == "" {
		job = "default"
	}
	
	return ExampleClient{
		Name: name,
		Job:  job,
	}
}

func main() {
	e1 := NewExampleClient("", "")
	fmt.Println(e1.Name, e1.Job)

	e2 := NewExampleClient("Alnk", "IT")
	fmt.Println(e2.Name, e2.Job)
}

举例2

有一种优雅的实现方法,叫做 Functional Options Patter。Functional Options 可以用来实现简洁的支持默认参数的函数方法。

这样利用闭包的特性,当我们需要额外添加参数时,只需要增加配置选项函数即可,拓展性很强。

// ExampleClient 定义结构体
type ExampleClient struct {
	Name string
	Job  string
}

//=============================================================================
//Option 定义配置选项函数(关键)
type Option func(*ExampleClient)

// SetName ...
func SetName(name string) Option { // 返回一个Option类型的函数(闭包):接受ExampleClient类型指针参数并修改
	return func(e *ExampleClient) {
		e.Name = name
	}
}

// SetJob ...
func SetJob(job string) Option {
	return func(e *ExampleClient) {
		e.Job = job
	}
}
//=============================================================================

// NewExampleClient 应用函数选项配置
func NewExampleClient(opts ...Option) ExampleClient {
	// 初始化默认值
	defaultClient := ExampleClient{
		Name: "default",
		Job:  "default",
	}

	// 依次调用opts函数列表中的函数,为结构体成员赋值
	for _, opt := range opts {
		opt(&defaultClient)
	}

	return defaultClient
}

func main() {
	e := NewExampleClient(SetName("Alnk"), SetJob("IT"))
	fmt.Println(e.Name, e.Job) // Alnk IT

	e2 := NewExampleClient()
	fmt.Println(e2.Name, e2.Job) // default default

	e3 := NewExampleClient(SetName("Alnk"))
	fmt.Println(e3.Name, e3.Job) // Alnk default

}
posted @ 2022-12-12 15:17  李成果  阅读(385)  评论(0编辑  收藏  举报