How it works...
The preceding code proposes the solution on executing multiple tasks that output some results, and we need only the first fastest one. The solution uses the Context with the cancel function to call cancel once the first result is obtained. The SearchSrc structure provides the Search method that results in a channel where the result is written. Note that the Search method simulates the delay with the time.Sleep function. The merge function, for each channel from the Search method, triggers the goroutine that writes to the final output channel that is read in the main method. While the first result is received from the output channel produced from the merge function, the CancelFunc stored in the variable cancel is called to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access