create a goroutine with a function in go

To create a goroutine in Go, you need to use the keyword go followed by the function you want to execute concurrently. Here's an example:

main.go
package main

import (
    "fmt"
)

func main() {
    // call the goroutine
    go printHelloWorld()

    // print from the main function
    fmt.Println("Printing from main function")
}

func printHelloWorld() {
    fmt.Println("Hello, World!")
}
248 chars
18 lines

In the above code, we called the printHelloWorld() function using the keyword go. This tells Go to execute that function in a separate goroutine, allowing the main() function to continue.

When we run this program, we will get the following output:

main.go
Printing from main function
Hello, World!
42 chars
3 lines

Notice that "Printing from main function" is printed first, followed by "Hello, World!", which was printed from the goroutine.

It's important to note that as soon as the main function exits, all goroutines are terminated, even if they haven't finished executing. Therefore, you have to make sure that your main function waits for the goroutines to finish before exiting. There are several ways to achieve this, but one common way is by using channels.

gistlibby LogSnag