Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A directional channel in Go is a channel type constrained at compile-time to permit only unidirectional data flow—either sending or receiving. By restricting a channel’s operations via its type signature, Go enforces type safety and prevents invalid operations, such as writing to a channel that should only be read from, or closing a channel from the receiving end.

Syntax and Type Signatures

Directionality is defined by the position of the arrow operator (<-) relative to the chan keyword. The arrow visually represents the direction of data flow.
chan T     // Bidirectional: permits sending, receiving, and closing
chan<- T   // Send-only: permits sending and closing; prohibits receiving
<-chan T   // Receive-only: permits receiving; prohibits sending and closing

Type Conversion and Assignment

Go allows implicit, one-way type conversion from a bidirectional channel to a directional channel. This typically occurs at function boundaries where a bidirectional channel is passed as an argument to a parameter expecting a directional channel.
bi := make(chan int)

// Implicit conversion from bidirectional to directional
var sendOnly chan<- int = bi
var recvOnly <-chan int = bi
The reverse is strictly prohibited. A directional channel cannot be cast or converted back into a bidirectional channel, nor can a send-only channel be converted to a receive-only channel.
// Compile-time errors:
// bi = sendOnly 
// bi = (chan int)(recvOnly)

Operation Constraints

The Go compiler enforces strict rules based on the channel’s directional type. Violating these rules results in compile-time errors, not runtime panics.

Receive-Only Channels (<-chan T)

  • Allowed: Reading data (val := <-ch), reading with the comma-ok idiom (val, ok := <-ch), and iterating via range.
  • Prohibited: Sending data (ch <- val) and closing the channel (close(ch)).

Send-Only Channels (chan<- T)

  • Allowed: Sending data (ch <- val) and closing the channel (close(ch)).
  • Prohibited: Reading data (<-ch) and iterating via range.

Mechanical Demonstration

The following code block illustrates the compiler enforcement of directional channel constraints within a function scope:
func enforceDirection(in <-chan int, out chan<- int) {
    // VALID OPERATIONS
    val := <-in      // Reading from receive-only
    out <- val       // Writing to send-only
    close(out)       // Closing send-only

    // INVALID OPERATIONS (Will cause compile-time errors)
    // in <- 1       // invalid operation: in <- 1 (send to receive-only type <-chan int)
    // close(in)     // invalid operation: close(in) (cannot close receive-only channel)
    // <-out         // invalid operation: <-out (receive from send-only type chan<- int)
}
Master Go with Deep Grasping Methodology!Learn More