Skip to content

Instantly share code, notes, and snippets.

@AndreKR
Last active March 19, 2017 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreKR/2423bd8df67453602112a6c6986b847e to your computer and use it in GitHub Desktop.
Save AndreKR/2423bd8df67453602112a6c6986b847e to your computer and use it in GitHub Desktop.
Returning result and error through a channel
// (I prefer "Two channels wrapped" and "Anonymous struct" over the other two)
// Two channels
resultCh := make(chan Result)
errorCh := make(chan Result)
go func(resultCh chan Result, errorCh chan errpr) {
errorCh <- errors.New("Does not compute")}
resultCh <- result
}(resultCh, errorCh)
select {
case result := <- resultCh:
...
case err := <- errorCh:
fmt.Println(err.Error())
}
// Two channels wrapped
func doStuffAsynchronously() (chan Result, chan error) {
resultCh := make(chan Result)
errorCh := make(chan error)
go func() {
errorCh <- errors.New("Does not compute")}
resultCh <- result
}()
}
resultCh, errorCh := doStuffAsynchronously()
select {
case result := <- resultCh:
...
case err := <- errorCh:
fmt.Println(err.Error())
}
// Anonymous struct
ch := make(chan struct{Result, error})
go func(ch chan struct{Result, error}) {
<- struct{Result; error}{Result{}, errors.New("Does not compute")}
<- struct{Result; error}{result, nil}
}(ch)
r := <-ch
if r.error != nil {
fmt.Println(r.error.Error())
}
result := r.Result
// Empty interface and type assertion
ch := make(chan interface{})
go func(ch chan interface{}) {
<- errors.New("Does not compute")
<- result
}(ch)
switch r := (<-ch).(type) {
case Result:
...
case error:
fmt.Println(r.Error())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment