ProgramGuru

Sending and Receiving Data

Start with Sending and Receiving Data

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

What you’ll learn

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

Understand the idea

A function can require a send-only channel (chan<- T) or a receive-only channel (<-chan T). These types express who is responsible for producing and consuming values.

Conversions from a bidirectional channel to directional parameters prevent accidental misuse in a helper function.

Visualize how it works

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

Visual explanation for channel directionsDirection types document responsibilities.Send-only producerStep 1Channel handoffStep 2Receive-only consumerStep 3Print 42Step 4Direction types document responsibilities.
Direction types document responsibilities.

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 produce(out chan<- int)    { out <- 21 }
func consume(in <-chan int) int { return (<-in) * 2 }
func main() {
	values := make(chan int)
	go produce(values)
	fmt.Println(consume(values))
}

Output

42

Trace what the program does

produce can only send, while consume can only receive. The transmitted 21 is doubled to 42.

Avoid common mistakes

  • A send-only function parameter cannot receive from its channel.
  • Avoid letting many goroutines close a channel they do not own.

Try it yourself

Type a channel pipeline with two helpers: one produces a number and the other prints it.

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

Check your understanding

What does chan permit?
Choose one answer. You can try again.

Answer and explanation

Sending int values

Correct. produce can only send, while consume can only receive.

What you should remember

You have practiced Sending and Receiving Data 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: Closing Channels →