Go Channels

What is a Channel?

A channel is used to send and receive data between goroutines.

It provides a safe way to communicate without shared memory.

Loading...
Output:

Creating a Channel

Channels are created using the make() function.

You must specify the type of data the channel will carry.

Loading...
Output:

Sending Data

Use the <- operator to send data into a channel.

The operation will block until another goroutine is ready to receive.

Loading...
Output:

Receiving Data

You can receive data from a channel using the same <- operator.

This will block until data is available.

Loading...
Output:

Complete Example

This example shows sending and receiving data between a goroutine and main.

Loading...
Output:

Blocking Behavior

Channels are blocking by default.

This means sending or receiving will wait until the other side is ready.

Loading...
Output:

Buffered Channels

Buffered channels allow storing a limited number of values without blocking immediately.

They are created by adding a size to make().

Loading...
Output:

Using Channels with Goroutines

Channels are commonly used to coordinate work between goroutines.

This ensures safe communication and synchronization.

Loading...
Output:

Why Channels Matter

Channels are a core part of Go’s concurrency model.

  • Prevent race conditions
  • Enable safe communication
  • Coordinate concurrent tasks

Common Mistakes

Be careful with these:

  • Deadlocks (no sender/receiver)
  • Forgetting to use goroutines
  • Using channels incorrectly with blocking behavior

Practice

Create a goroutine that sends a number through a channel and print it in main.

Loading...
Output:

Need Help?