-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct_func_options.go
63 lines (49 loc) · 935 Bytes
/
struct_func_options.go
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import "fmt"
// Efficient struct pattern (Functional Options)
// learn more: https://www.youtube.com/watch?v=MDy7JQN5MN4
type OptFunc func (*Opts)
type Opts struct {
maxConn int
id string
tls bool
}
func defaultOpts() Opts {
return Opts {
maxConn: 10,
id: "default",
tls: false,
}
}
func withId(s string) OptFunc {
return func(opts *Opts) {
opts.id = s
}
}
func withTLS(opts *Opts) {
opts.tls = true
}
func withMaxConn(n int) OptFunc{
return func(opts *Opts) {
opts.maxConn = n
}
}
type Server struct {
Opts
}
func newServer(opts ...OptFunc) *Server{
o := defaultOpts()
// if opts is not provided we use the defaultOpts
// if opts are provided we can modify option pointers
for _, fn := range opts {
fn(&o)
}
return &Server{
Opts: o,
}
}
func FuncMain() {
// s := newServer() Default Options
s := newServer(withTLS, withMaxConn(99), withId("sishir"))
fmt.Println(s)
}