Go by Example: Channel Directions

package main

import "fmt"

// A function that takes a channel as an argument can receive values from it.
func ping(pings chan<- string, msg string) {
	pings <- msg
}

// A function that takes two channels as arguments can receive and send values from/to these channels.
func pong(pings <-chan string, pongs chan<- string) {
	msg := <-pings
	pongs <- msg
}

func main() {
	pings := make(chan string, 1)
	pongs := make(chan string, 1)
	ping(pings, "passed message")
	pong(pings, pongs)
	fmt.Println(<-pongs)
}

This program demonstrates the use of channel directions. The ping function takes a channel pings of type chan<- string, meaning it can only send strings to it. The pong function takes two channels, pings of type <-chan string, meaning it can only receive strings from it, and pongs of type chan<- string, meaning it can only send strings to it. The main function creates two channels, pings and pongs, and uses the ping and pong functions to send and receive values from the channels. The program outputs: passed message.

Here’s an example of using channel directions to ensure data flows only in one direction:

package main

import "fmt"

func ping(pings chan<- string, msg string) {
    pings <- msg
}

func pong(pings <-chan string, pongs chan<- string) {
    msg := <-pings
    pongs <- msg
}

func main() {
    pings := make(chan string, 1)
    pongs := make(chan string, 1)
    ping(pings, "passed message")
    pong(pings, pongs)
    fmt.Println(<-pongs)
}

In this example, the ping function can only send values to the pings channel and the pong function can only receive values from the pings channel and send values to the pongs channel. This ensures that data flows in a specific direction and prevents potential bugs caused by concurrent access to the channels.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *