Idiomatic way to return error/success from async function / go routine

Viewed 323

I'm just looking into go routines and channels and have a question about returning errors:

Where I have result or error I do the following:

func Do() (int,error)

becomes

func DoAsync() (<-chan int, <-chan error)

where the function writes the result or error to the correct channel and the caller selects on both channels

However, I'm not sure how to handle the case where the result is simply success or failure

func Do() error

I would normally return error or nil for success

func DoAsync() <-chan error

I can follow the same idiom and write error or nil to the channel but this seems clunky - In the first case, I would only write result OR error (not result and nil to error channel) For success I could simply close the channel with no error but then I'm stuck as to how to read this. I can read the error or for an error in the channel (ie closed) but this seems even more clunky

What is the best, idiomatic way, to achieve this?

I have googled many examples but they all seem to focus on either result channel only or result/error channels (or result and error sharing a channel with a struct)

0 Answers
Related