Is there a way to run a for loop as a go routine without putting it in a separate func

StackOverflow https://stackoverflow.com/questions/18624296

  •  27-06-2022
  •  | 
  •  

Вопрос

Let's say I want to set a for loop running but don't want to block the execution, obviously I can put the for loop in a function f and call go f and continue with my life,
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")
Это было полезно?

Решение 2

If you want to run each loop in the background, nest the goroutine in 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")

Другие советы

The only way to do this is indeed by creating a function around it. In your example this is how you would 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")

Make note of the actual calling of the function at the end }(). As otherwise the compiler will complain to you.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top