ProgramGuru

Creating Goroutines

Start with Creating Goroutines

In this lesson, explore creating 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 creating goroutines.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Goroutines can use named functions or function literals. Pass changing loop values as arguments to make their intended values explicit.

When many results arrive in arbitrary order, store them by index so output stays meaningful. This matters more than assuming one goroutine will run first.

Visualize how it works

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

Visual explanation for create goroutinesResults can be ordered even when execution is not.Launch 3 workersStep 1Calculate squaresStep 2Collect indexed resultsStep 3Restore input orderStep 4Results can be ordered even when execution is not.
Results can be ordered even when execution is not.

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"

type Result struct{ Index, Square int }

func main() {
	ch := make(chan Result, 3)
	for i := 1; i <= 3; i++ {
		go func(n int) { ch <- Result{n - 1, n * n} }(i)
	}
	squares := make([]int, 3)
	for range squares {
		r := <-ch
		squares[r.Index] = r.Square
	}
	fmt.Println(squares)
}

Output

[1 4 9]

Trace what the program does

Each worker captures its input through an argument, then returns its index and square. The main goroutine reconstructs [1 4 9] regardless of completion order.

Avoid common mistakes

  • Do not rely on goroutine completion order.
  • For long-running tasks, create a bounded amount of work rather than unlimited goroutines.

Try it yourself

Launch workers for numbers 1 through 5 and collect five ordered square values.

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

Check your understanding

Why include an index in each result?
Choose one answer. You can try again.

Answer and explanation

To restore input order after concurrent work

Correct. Each worker captures its input through an argument, then returns its index and square.

What you should remember

You have practiced Creating 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: Goroutine Lifecycle →