Last active
March 19, 2017 18:44
-
-
Save AndreKR/2423bd8df67453602112a6c6986b847e to your computer and use it in GitHub Desktop.
Returning result and error through a channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (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