ProgramGuru

Context in Go

Start with Context in Go

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

What you’ll learn

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

Understand the idea

context.Context carries cancellation signals, deadlines and request-scoped values through call chains. Pass it as the first parameter to operations that can block or must stop with their caller.

A Context is not a generic settings bag. Use WithValue for request-scoped metadata when truly needed, not ordinary function inputs.

Visualize how it works

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

Visual explanation for contextA call tree shares one cancellation contract.Caller owns contextStep 1Pass to helperStep 2Helper checks DoneStep 3Return or stopStep 4A call tree shares one cancellation contract.
A call tree shares one cancellation contract.

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 (
	"context"
	"fmt"
)

func label(ctx context.Context) string {
	if err := ctx.Err(); err != nil {
		return "stopped"
	}
	return "running"
}
func main() {
	ctx := context.Background()
	fmt.Println("Task:", label(ctx))
}

Output

Task: running

Trace what the program does

Background returns a base context with no cancellation. Err is nil, so the helper returns running.

Avoid common mistakes

  • Do not store a context in a long-lived struct without a specific design reason.
  • Do not pass nil for Context; use context.Background or context.TODO.

Try it yourself

Add a context parameter to a function that validates whether work should continue.

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

Check your understanding

What belongs in a Go context?
Choose one answer. You can try again.

Answer and explanation

Cancellation and deadline signals

Correct. Background returns a base context with no cancellation.

What you should remember

You have practiced Context in Go 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: Context Cancellation →