DEV Community

Santosh Anand
Santosh Anand

Posted on

Read data from channel Golang

Step 1: Create a Go Project
First, set up your Go environment if you haven't already. You can follow the installation guide here.

Create a new Go project directory:

mkdir go_channel_example
cd go_channel_example
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Main Go File
Create a file named main.go in your project directory.

Step 3: Write the Code to Use Channels
Below is an example Go program that demonstrates how to create a channel, send data to the channel, and read data from the channel.

package main

import (
    "fmt"
    "time"
)

// Worker function that sends data to a channel
func worker(id int, ch chan<- string) {
    for i := 0; i < 5; i++ {
        message := fmt.Sprintf("Worker %d: message %d", id, i)
        ch <- message
        time.Sleep(time.Millisecond * 500)
    }
    close(ch)
}

func main() {
    // Create a channel to communicate strings
    messageChannel := make(chan string)

    // Start a goroutine that sends data to the channel
    go worker(1, messageChannel)

    // Read data from the channel
    for message := range messageChannel {
        fmt.Println(message)
    }

    fmt.Println("Done receiving messages")
}
Enter fullscreen mode Exit fullscreen mode

Explanation
Channel Creation:

messageChannel := make(chan string)
Enter fullscreen mode Exit fullscreen mode

This line creates a channel named messageChannel that can transfer strings.

Sending Data to the Channel:

go worker(1, messageChannel)
Enter fullscreen mode Exit fullscreen mode

This line starts a new goroutine that runs the worker function. The worker function sends strings to the messageChannel.

Reading Data from the Channel:

for message := range messageChannel {
    fmt.Println(message)
}
Enter fullscreen mode Exit fullscreen mode

This loop reads messages from the messageChannel until the channel is closed. The range keyword allows you to receive values from the channel until it is closed.

Closing the Channel:

close(ch)
Enter fullscreen mode Exit fullscreen mode

The worker function closes the channel after sending all its messages. This is important because it signals to the receiver that no more data will be sent.

Running the Program
To run the program, open a terminal in your project directory and execute:

go run main.go
Enter fullscreen mode Exit fullscreen mode

You should see the output similar to the following, demonstrating that data is being sent to and received from the channel:

Worker 1: message 0
Worker 1: message 1
Worker 1: message 2
Worker 1: message 3
Worker 1: message 4
Done receiving messages
Enter fullscreen mode Exit fullscreen mode

Summary
This example shows how to use Go channels to send and receive data between goroutines. Channels provide a powerful way to synchronize and communicate between different parts of a Go program, ensuring safe data exchange without explicit locks.

Top comments (0)