-2

Can someone explain how this works:

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    say("world")
}

But this doesnt work once i add the word go to the routine in main

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
}

I think its because its finishing before executing the goroutine.

somejkuser
  • 8,856
  • 20
  • 64
  • 130

1 Answers1

3

The "world" goroutine does not run or complete because main returns and the program exits.

When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete. https://golang.org/ref/spec#Program_execution

IceLady
  • 186
  • 1
  • 1
  • 7