English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String

Golang Pointer

Golang Interface

Golang Concurrency

Golang Error

Golang Other Miscellaneous

Go Language Unidirectional Channel

As is well known, channels are the communication medium between concurrently running goroutines, so they can send and receive data to each other. By default, channels are bidirectional, but you can also create unidirectional channels. Channels that can only receive data or can only send data areUnidirectional channel. Unidirectional channels can also be created using the make() function, as shown below:

//Used only for receiving data
c1:= make(<- chan bool)
//Used only for sending data
c2:= make(chan<-bool)

Example of unidirectional channel usage1:

package main 
  
import "fmt"
  
func main() { 
  
    //Used only for receiving data
    mychanl1 := make(<-chan string) 
  
    //Used only for sending data
    mychanl2 := make(chan<- string) 
  
    //Display the type of the channel 
    fmt.Printf("%T", mychanl1) 
    fmt.Printf("\n%T", mychanl2) 
}

Output:

<-chan string
chan<- string

Convert bidirectional channels to unidirectional channels

In Go language, it is allowed to convert bidirectional channels to unidirectional channels, in other words, you can convert bidirectional channels to receive-only or send-only channels, but vice versa. As shown in the following program:

package main 
  
import "fmt"
  
func sending(s chan<- string) { 
    s <- "w3codebox"
} 
  
func main() { 
  
    //Creating a bidirectional channel
    mychanl := make(chan string) 
  
        //In this case, the sending() function converts a bidirectional channel to a unidirectional send-only channel 
    go sending(mychanl) 
  
    //In this case, the channel is only used for sending within the goroutine, and it is bidirectional outside the goroutine, so it prints w3codebox 
    fmt.Println(<-mychanl) 
}

Output:

w3codebox

Usage of unidirectional channels:Unidirectional channels are used to provide type safety for programs, resulting in fewer errors generated by the program. Alternatively, you can also use unidirectional channels when you want to create channels that can only send or receive data.