ProgramGuru

Introduction to Channels

Start with Introduction to Channels

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

Understand the idea

A channel is a typed communication path between goroutines. A send uses ch <- value, and a receive uses value := <-ch.

Channel operations also provide synchronization. Channels are especially useful when one goroutine owns the task of producing data and another consumes it.

Visualize how it works

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

Visual explanation for channelsA channel carries both a typed value and synchronization.Create channelStep 1Producer sendsStep 2Consumer receivesStep 3Use messageStep 4A channel carries both a typed value and synchronization.
A channel carries both a typed value and 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 main() {
	messages := make(chan string)
	go func() { messages <- "ready" }()
	message := <-messages
	fmt.Println("Message:", message)
}

Output

Message: ready

Trace what the program does

The unbuffered send waits until the receiver is available. The receive transfers ready and the program prints Message: ready.

Avoid common mistakes

  • A channel’s element type is fixed.
  • Closing a channel is not required simply because its last send finished.

Try it yourself

Change the channel to carry an int, send 42, and print the received value.

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

Check your understanding

What does mean in the sample?
Choose one answer. You can try again.

Answer and explanation

Receive a value from messages

Correct. The unbuffered send waits until the receiver is available.

What you should remember

You have practiced Introduction to Channels 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: Unbuffered Channels →