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.go248 chars18 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.go42 chars3 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