ProgramGuru

Introduction to Goroutines

Start with Introduction to Goroutines

In this lesson, explore introduction to goroutines through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of introduction to goroutines.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Prefix a function call with go to launch it as a goroutine. It shares the process address space with other goroutines but has its own execution stack.

A goroutine does not return its function result to the caller. Use channels or other synchronization to communicate and wait.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for goroutinesThe receive also establishes the required synchronization.go greet(done)Step 1Goroutine sendsStep 2Main receivesStep 3Print messageStep 4The receive also establishes the required synchronization.
The receive also establishes the required synchronization.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func greet(done chan<- string) { done <- "Hello from a goroutine" }
func main() {
	done := make(chan string)
	go greet(done)
	fmt.Println(<-done)
}

Output

Hello from a goroutine

Trace what the program does

The new goroutine sends a string through done. main receives the string, blocking until the send is ready, then prints it.

Avoid common mistakes

  • A bare go statement does not wait for completion.
  • Sending or receiving through a nil channel blocks indefinitely.

Try it yourself

Change greet to accept a name and send a personalized message.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

How does main obtain this goroutine’s message?
Choose one answer. You can try again.

Answer and explanation

By receiving from its channel

Correct. The new goroutine sends a string through done.

What you should remember

You have practiced Introduction to Goroutines in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Creating Goroutines →