go语言设计模式之Concurrency future
Posted aguncn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言设计模式之Concurrency future相关的知识,希望对你有一定的参考价值。
future.go
package future type SuccessFunc func(string) type FailFunc func(error) type ExecuteStringFunc func() (string, error) type MaybeString struct { successFunc SuccessFunc failFunc FailFunc } func (s *MaybeString) Success(f SuccessFunc) *MaybeString { s.successFunc = f return s } func (s *MaybeString) Fail(f FailFunc) *MaybeString { s.failFunc = f return s } func (s *MaybeString) Execute(f ExecuteStringFunc) { go func(s *MaybeString) { str, err := f() if err != nil { s.failFunc(err) } else { s.successFunc(str) } }(s) }
future_test.go
package future import ( "errors" "sync" "testing" "time" ) func TestStringOrError_Execute(t *testing.T) { future := &MaybeString{} t.Run("Success result", func(t *testing.T) { var wg sync.WaitGroup wg.Add(1) go timeout(t, wg) future.Success(func(s string) { t.Log(s) wg.Done() }).Fail(func(e error) { t.Fail() wg.Done() }) future.Execute(func() (string, error) { return "Hello World!", nil }) wg.Wait() }) t.Run("Error result", func(t *testing.T) { var wg sync.WaitGroup wg.Add(1) future.Success(func(s string) { t.Fail() wg.Done() }).Fail(func(e error) { t.Log(e.Error()) wg.Done() }) future.Execute(func() (string, error) { return "", errors.New("Error ocurred") }) wg.Wait() }) } func timeout(t *testing.T, wg sync.WaitGroup) { time.Sleep(time.Second) t.Log("Timeout") t.Fail() wg.Done() }
以上是关于go语言设计模式之Concurrency future的主要内容,如果未能解决你的问题,请参考以下文章
go语言设计模式之Concurrency workers pool