[Solved] Why can’t this program print anything using goroutine? [duplicate]


Your code needs to wait for the routines to finish before exiting. A good way to do this is to pass in a channel which is used by the routine to signal when it’s done and then wait in the main code. See below.

Another advantage of this approach is that it allows/encourages you to perform proper error handling based on the return value.

package main

import (
    "fmt"
)

func f(msg string, quit chan int) {
    fmt.Println(msg)
    quit <- 0
    return
}

func main() {

    ch1 := make(chan int)
    ch2 := make(chan int)

    go f("goroutine", ch1)

    go func(msg string, quit chan int) {
        fmt.Println(msg)
        quit <- 0
        return
    }("going", ch2)

    <-ch1
    <-ch2
    return
}

solved Why can’t this program print anything using goroutine? [duplicate]