CodeBlanks Logo Icon CodeBlanks

Receiving data

Learn to receive data from a channel with <-.

Receiving data

To receive from a channel use the same <- operator: v := <-ch. This takes a value from ch and assigns it to v. In an unbuffered channel it blocks until a sender is ready.

The receive expression is v := <-ch. The arrow points out of the channel. You can print directly with fmt.Println(<-ch). A closed channel returns the zero value.

Receive and block

In an unbuffered channel the receiver blocks until a sender is ready. This makes the channel a synchronization tool: both wait until they meet.

With v, ok := <-ch you learn whether the channel is open or closed. If ok is false the channel is closed and drained. This pattern detects channel closure.

Practice Receive from a channel

Inside main, add a <-ch expression and print received with fmt.Println.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    ch := make(chan string)
    go func() { ch <- "alındı" }()
    fmt.Println(<-ch)
}

Expected output

alındı

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does v := <-ch do?

  • Closes ch
  • Receives from ch into v Correct answer
  • Deletes v
  • Sends v on ch

Explanation: receives from ch into v. Sending is ch <- v.

2 Receive expression

Question
v := ____ch
Answer
v := <-ch

Explanation: The same operator is used for send and receive.

3 Match receive concepts

Term Meaning
<-ch Receive
v, ok Status check
block Wait
closed Zero value

All lessons in Intermediate