go-选项卡模式
package main import "fmt" const ( defaultName string = "张建平" defaultAge int = 27 defaultHigh int = 175 ) type User struct { Name string Age int High int } type UserOptions struct { Name string Age int High int } type UserOption interface { apply(*UserOptions) } type FuncUserOption struct { f func(*UserOptions) } func (fo FuncUserOption) apply(option *UserOptions) { fo.f(option) } func WithName(name string) UserOption { return FuncUserOption{ f: func(options *UserOptions) { options.Name = name }, } } func WithAge(age int) UserOption { return FuncUserOption{ f: func(options *UserOptions) { options.Age = age }, } } func WithHigh(high int) UserOption { return FuncUserOption{f: func(options *UserOptions) { options.High = high }} } func NewUser(opts ...UserOption) *User { options := UserOptions{ Name: defaultName, Age: defaultAge, High: defaultHigh, } for _, opt := range opts { opt.apply(&options) } return &User{ Name: options.Name, Age: options.Age, High: options.High, } } func main() { u1 := NewUser() fmt.Println(u1) u2 := NewUser(WithName("胖虎")) fmt.Println(u2) u3 := NewUser(WithName("喵"), WithAge(3)) fmt.Println(u3) }
package main import ( "fmt" "sync" ) var wg sync.WaitGroup const repeatCount = 100 func main() { // cat dog fish catCh := make(chan struct{}, 1) dogCh := make(chan struct{}, 1) fishCh := make(chan struct{}, 1) wg.Add(3) catCh <- struct{}{} go printAnimal(catCh, dogCh, "cat", &wg) go printAnimal(dogCh, fishCh, "dog", &wg) go printAnimal(fishCh, catCh, "fish", &wg) wg.Wait() } func printAnimal(in, out chan struct{}, name string, wg *sync.WaitGroup) { count := 0 for { <-in count++ fmt.Println(name) out <- struct{}{} if count >= repeatCount { wg.Done() return } } }
本文来自博客园,作者:一石数字欠我15w!!!,转载请注明原文链接:https://www.cnblogs.com/52-qq/p/17515434.html