在Golang中初始化struct之后如何优雅的设置一些字段的值.现在来学习下k8s源码中是如何做的
| 1 | package main | 
另外一种类似的方法,相当于省略了Apply函数,将Apply函数的内容写在了WithClientSet函数中。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
33
34package main
import "fmt"
type frameworkOptions struct {
	clientSet 	string
}
type fOption func(*frameworkOptions)
func WithClientSet(clientSet string) fOption  {
	return func(o *frameworkOptions) {
		o.clientSet = clientSet
	}
}
func newFrameWork(opts ...fOption) *frameworkOptions  {
	fr := &frameworkOptions{
		clientSet: "Cat",
    }
    // 执行额外的赋值操作,通过opts中的内容修改frameworkOptions中的值
	for _,opt := range opts {
		opt(fr)
	}
	return fr
}
func main() {
    opts := []fOption{WithClientSet("Dog")}
    r := newFrameWork(options...)
    fmt.Println(r) // &{Dog}
}