Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you use channels for bidirectional communication in Go


Can you use channels for bidirectional communication in Go


Yes, Go channels can be used for bidirectional communication. A bidirectional channel in Go is a channel that can be used for both sending and receiving values. It is declared using the keyword "chan" followed by the type of the values that will be sent over the channel. For example, a bidirectional channel of type string would be declared as `chan string`.

Here is a simple example of a bidirectional channel in Go:

go
package main

import "fmt"

func main() {
    // Create a bidirectional channel
    ch := make(chan string)

    // Start a goroutine
    go func() {
        // Send data to the channel
        ch <- "Hello, world!"
    }()

    // Receive data from the channel
    fmt.Println(<-ch)
}

In this example, the channel `ch` is used for both sending and receiving data. The goroutine sends the string "Hello, world!" to the channel, and the main goroutine receives it.

Converting Bidirectional Channel into Unidirectional Channel

In Go, a bidirectional channel can be converted into a unidirectional channel, but not the other way around. Here is an example of converting a bidirectional channel into a send-only channel:

go
package main

import "fmt"

func main() {
    // Create a bidirectional channel
    ch := make(chan string)

    // Convert the channel into a send-only channel
    sendOnlyCh := make(chan string)

    // Start a goroutine
    go func() {
        // Send data to the send-only channel
        sendOnlyCh <- "Hello, world!"
    }()

    // Send data to the bidirectional channel
    ch <- "Hello, Go!"

    // Receive data from the bidirectional channel
    fmt.Println(<-ch)
}

In this example, the bidirectional channel `ch` is converted into a send-only channel `sendOnlyCh`. The goroutine sends data to `sendOnlyCh`, but it cannot receive data from it because it is a send-only channel.

Citations:
[1] https://www.scaler.com/topics/golang/directional-channel-in-golang/
[2] https://dev.to/neeraj1997dev/concurrency-in-go-2go-channels-24lk
[3] https://coffeebytes.dev/en/go-use-of-channels-to-communicate-goroutines/
[4] https://blog.logrocket.com/how-use-go-channels/
[5] https://www.reddit.com/r/golang/comments/pxmyvp/communicate_across_network_using_go_channels/