RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 22: Channel Direction in Go – Send Only? Receive Only?

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

“This function should only SEND on a channel. How do I make sure no one misuses it?”

In Go, you can restrict what a function does with a channel:

  • Only send

  • Only receive

Let’s dive in like a 12-year-old 😄

You give your little brother a walkie-talkie.
You tell him:

🗣️ “ONLY talk, don’t listen!”

or

👂 “ONLY listen, don’t talk!”

That’s channel direction.

Here’s how we write that in Go:

// Send-only
func sayHi(ch chan<- string) {
  ch <- "hi"
}
// Receive-only
func listen(ch <-chan string) {
  msg := <-ch
  fmt.Println("Heard:", msg)
}

See the arrows?

  • chan<- string: send-only

  • <-chan string: receive-only

By being strict:

  • Your code is safer

  • You prevent mistakes (like receiving when you should only send)

  • You make intentions clear to teammates (or future-you)

package main
import "fmt"
func sendMessage(ch chan<- string) {
  ch <- "Hello!"
}
func receiveMessage(ch <-chan string) {
  msg := <-ch
  fmt.Println("Got:", msg)
}
func main() {
  c := make(chan string)
  go sendMessage(c)
  receiveMessage(c)
}

Output:

Got: Hello!

Try receiving in sendMessage():

msg := <-ch // ❌ won't compile!

Go will yell:

“Invalid operation: cannot receive from send-only channel”

Same if you try to send on a receive-only one.

Use direction when:

  • Writing functions that only send or receive

  • Building pipelines with multiple steps

  • Passing channels around safely

You can assign a bidirectional channel to a directional one:

ch := make(chan string)
var sendOnly chan<- string = ch
var recvOnly <-chan string = ch

But you can’t do it the other way around!

  • Use chan<- to send only

  • Use <-chan to receive only

  • Helps keep your code safe, clear, and intentional

No posts

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.