函数式参数
Functional Options Pattern / 函数式选项模式
- 延迟配置(deferred config)
- 可选参数(optional params)
- 行为组合(composable behavior)
go
type Option func(*fields)
type fields struct {
status string
err error
}
func WithStatus(status string) Option {
return func(f *fields) {
f.status = status
}
}
func WithErr(err error) Option {
return func(f *fields) {
f.err = err
}
}
func Log(action string, opts ...Option) {
f := &fields{}
for _, opt := range opts {
opt(f) // 执行函数,修改 f
}
fmt.Println(f.status, f.err)
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
考虑是否使用
参数是否:
- 可选?
- 会扩展?
- 顺序不重要?