Is there a way to run a for loop as a subroutine without putting it in a separate function

Let's say I want to set for loop, but do not want to block the execution, it is obvious that I can put the for loop in the function f and the cause go f and continue their lives,
but I was curious if there is a way to call go for directly, something like:

 fmt.Println("We are doing something") //line below is my question go for i := 1; i < 10; i ++ { fmt.Println("stuff running in background") } // life goes on fmt.Println("c'est la vie") 
+4
source share
2 answers

If you want to run each loop in the background, insert goroutine into the loop and use the sync.WaitGroup structure.

 import "sync" fmt.Println("We are doing something") //line below is my question wg := sync.WaitGroup{} // Ensure all routines finish before returning defer wg.Wait() for i := 1; i < 10; i ++ { wg.Add(1) go func() { defer wg.Done() fmt.Println("stuff running in background") }() } // life goes on fmt.Println("c'est la vie") 
+3
source

The only way to do this is to create a function around it. In your example, this is how you do it.

 fmt.Println("We are doing something") //line below is my question go func() { for i := 1; i < 10; i ++ { fmt.Println("stuff running in background") } }() // life goes on fmt.Println("c'est la vie") 

Note the actual function call at the end }() . Otherwise, the compiler will complain to you.

+12
source

Source: https://habr.com/ru/post/1500617/


All Articles