有没有一种方法可以将for循环作为go例程运行而无需将其放在单独的func中

有没有一种方法可以将for循环作为go例程运行而无需将其放在单独的func中

问题描述:

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")

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.