Sending data
- Go course
- Intermediate
- Lesson 9/80
- 4 min
Learn to send data to a channel with the <- operator.
Sending data
To send data on a channel use the <- operator: ch <- 42. This sends 42 on the ch channel. In an unbuffered channel it blocks until a receiver is ready.
The send expression is ch <- value. Channel on the left, value on the right, arrow points in. Blocking makes the channel synchronous.
Send and block
In an unbuffered channel the sender blocks until a receiver is ready. This is a rendezvous between goroutines. The sender waits until a receiver appears.
This is useful for synchronization: the goroutine writing ch <- 1 does not proceed until another does <-ch. The two goroutines meet at that point.
Practice Send to a channel
Inside main, add a ch <- "sent" expression and print sent with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
ch := make(chan string)
go func() { ch <- "gönderildi" }()
fmt.Println(<-ch)
}Expected output
gönderildi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does ch <- 42 do?
- Receives 42 from ch
- Deletes 42
- Compares 42
- Sends 42 on ch Correct answer
Explanation: sends 42 on ch. An inward arrow means send.
2 Send expression
ch ____ 42
ch <- 42
Explanation: > is the wrong way, <= is comparison.
3 Match send concepts
| Term | Meaning |
|---|---|
ch <- v |
Send |
<- |
Operator |
block |
Wait |
receiver |
Consumer |