Thursday, July 10, 2025
HomeLanguagesGolangUnidirectional Channel in Golang

Unidirectional Channel in Golang

As we know that a channel is a medium of communication between concurrently running goroutines so that they can send and receive data to each other. By default a channel is bidirectional but you can create a unidirectional channel also. A channel that can only receive data or a channel that can only send data is the unidirectional channel. The unidirectional channel can also create with the help of make() function as shown below:

// Only to receive data
c1:= make(<- chan bool)

// Only to send data
c2:= make(chan<- bool)

Example 1: 

Go




// Go program to illustrate the concept
// of the unidirectional channel
package main
 
import "fmt"
 
// Main function
func main() {
 
    // Only for receiving
    mychanl1 := make(<-chan string)
 
    // Only for sending
    mychanl2 := make(chan<- string)
 
    // Display the types of channels
    fmt.Printf("%T", mychanl1)
    fmt.Printf("\n%T", mychanl2)
}


Output:

<-chan string
chan<- string

Converting Bidirectional Channel into the Unidirectional Channel

In Go language, you are allowed to convert a bidirectional channel into a unidirectional channel, or in other words, you can convert a bidirectional channel into a receive-only or send-only channel, but vice versa is not possible. As shown in the below program: 

Example: 

Go




// Go program to illustrate how to convert
// bidirectional channel into the
// unidirectional channel
package main
 
import "fmt"
 
func sending(s chan<- string) {
    s <- "GeeksforGeeks"
}
 
func main() {
 
    // Creating a bidirectional channel
    mychanl := make(chan string)
 
    // Here, sending() function convert
    // the bidirectional channel
    // into send only channel
    go sending(mychanl)
 
    // Here, the channel is sent
    // only inside the goroutine
    // outside the goroutine the
    // channel is bidirectional
    // So, it print GeeksforGeeks
    fmt.Println(<-mychanl)
}


Output:

GeeksforGeeks

Use of Unidirectional Channel: The unidirectional channel is used to provide the type-safety of the program so, that the program gives less error. Or you can also use a unidirectional channel when you want to create a channel that can only send or receive data.

RELATED ARTICLES

Most Popular

Dominic
32126 POSTS0 COMMENTS
Milvus
66 POSTS0 COMMENTS
Nango Kala
6510 POSTS0 COMMENTS
Nicole Veronica
11658 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11714 POSTS0 COMMENTS
Shaida Kate Naidoo
6605 POSTS0 COMMENTS
Ted Musemwa
6865 POSTS0 COMMENTS
Thapelo Manthata
6565 POSTS0 COMMENTS
Umr Jansen
6558 POSTS0 COMMENTS