-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopts.go
44 lines (40 loc) · 1.24 KB
/
opts.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
package opts
// Opt is a type alias for a func that manipulates your opts.
type Opt[T any] func(*T)
// OptionsDefaulter is a factory interface for creating the default of your options.
type OptionsDefaulter[T any] interface {
DefaultOptions() T
}
// DefaultApply uses the default factory to construct a default instance of the options and runs the Opt mutators on the
// result.
//
// func GetUser(userId string, op ...opts.Opt[GetUserOpts]) (*User, error) {
// o := opts.DefaultApply(op...)
// ...
// }
//
// type GetUserOpts struct {
// // Timeout if it takes longer than the specified time to get the user
// Timeout time.Duration
// }
//
// func (g GetUserOpts) DefaultOptions() GetUserOpts {
// return GetUserOpts{Timeout: 5 * time.Second}
// }
//
// func WithTimeout(t time.Duration) opts.Opt[GetUserOpts] {
// return func(o *GetUserOpts) {
// o.Timeout = t
// }
// }
func DefaultApply[T OptionsDefaulter[T]](opts ...Opt[T]) T {
a := (*new(T)).DefaultOptions()
Apply[T](&a, opts...)
return a
}
// Apply applies the mutator Opts to some instance of the options. See DefaultApply for a more in-depth example.
func Apply[T any](o *T, opts ...Opt[T]) {
for _, v := range opts {
v(o)
}
}