So, basically, is there any difference between these 2 blocks of code?
res := make(chan error, 1)
go func() {
res <- slowOperation()
}()
select {
case <-time.After(deadline):
return errors.New("deadline exceeded")
case err := <-res:
return err
}
and
res := make(chan error, 1)
select {
case <-time.After(deadline):
return errors.New("deadline exceeded")
case res <- slowOperation():
err := <-res
return err
}
Is it necessary to wrap a function in goroutine, as all of the examples on the Internet show, and if so, why?
>Solution :
Yes, there is a significant difference between the two blocks of code.
In the first block of code, you are creating a goroutine using go func() { ... }() to run slowOperation() asynchronously. The select block will wait for either the slowOperation() to complete or the deadline to be exceeded. If the deadline is exceeded, the function returns an error; otherwise, it returns the result of slowOperation().
In the second block of code, you are not using a goroutine to run slowOperation(); instead, it runs synchronously within the select block. This means that the time.After(deadline) case will not be evaluated until slowOperation() has completed, which effectively removes the deadline functionality.
In conclusion, using a goroutine is necessary when you want to execute a function asynchronously and evaluate multiple channels simultaneously in the select block, as shown in the first block of code.
Hoping it can help you.