BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Channels

Go 1.23

Understand Channels, the conduits that connect concurrent goroutines. This example demonstrates how to send and receive values to synchronize execution and share data safely without explicit locks, following Go's philosophy: "Do not communicate by sharing memory; instead, share memory by communicating."

Code

package main

import "fmt"

func main() {
    // Create a new channel of strings
    messages := make(chan string)

    // Send to channel in a goroutine
    go func() { 
        messages <- "ping" 
    }()

    // Receive from channel
    msg := <-messages
    fmt.Println(msg)
}

Explanation

Channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine. This mechanism allows for safe communication and synchronization without explicit locks.

Create a new channel with make(chan val-type). Channels are typed by the values they convey. By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.

Key channel operations:

  • ch <- v // Send v to channel ch
  • v := <-ch // Receive from ch, and assign value to v
  • close(ch) // Close the channel

Code Breakdown

7
Creating a channel that transports strings using make(chan string).
11
Sending a value into the channel using the <- syntax. This is done in a separate goroutine because unbuffered channel sends block until there is a receiver.
15
Receiving a value from the channel. This blocks until a value is sent. This synchronization ensures "ping" is printed only after it has been sent.