| 1 |
package main |
| 2 |
|
| 3 |
import "fmt" |
| 4 |
|
| 5 |
type Option func(*Struct) |
| 6 |
|
| 7 |
func WithOption(opt string) Option { |
| 8 |
return func(s *Struct) { |
| 9 |
s.opt = opt |
| 10 |
} |
| 11 |
} |
| 12 |
|
| 13 |
type Struct struct { |
| 14 |
opt string |
| 15 |
} |
| 16 |
|
| 17 |
func New(opts ...Option) *Struct { |
| 18 |
s := new(Struct) |
| 19 |
for _, opt := range opts { |
| 20 |
opt(s) |
| 21 |
} |
| 22 |
return s |
| 23 |
} |
| 24 |
|
| 25 |
func (s *Struct) ShowOption() { |
| 26 |
fmt.Println(s.opt) |
| 27 |
} |
| 28 |
|
| 29 |
func main() { |
| 30 |
opts := []Option{ |
| 31 |
WithOption("test"), |
| 32 |
} |
| 33 |
s := New(opts...) |
| 34 |
s.ShowOption() |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
|