Sending and receiving values lets different parts of a Go program talk to each other safely and clearly.
0
0
Sending and receiving values in Go
Introduction
When you want two parts of your program to share information without mixing things up.
When you need to do many things at the same time and want them to work together.
When you want to pass messages between different tasks running in your program.
When you want to wait for a result from another part before continuing.
When you want to control the flow of data between different parts of your program.
Syntax
Go
channel <- value // send value to channel value := <-channel // receive value from channel
Channels are like pipes that let you send and receive values between goroutines.
Use channel <- value to send and value := <- channel to receive.
Examples
Create a channel for integers, send 5 into it, then receive it into val.
Go
ch := make(chan int) // Sending ch <- 5 // Receiving val := <-ch
Send a string "hello" from a goroutine and receive it in the main goroutine.
Go
ch := make(chan string)
go func() {
ch <- "hello"
}()
msg := <-chSample Program
This program creates a channel for strings. A new goroutine sends a message through the channel. The main function waits to receive the message and then prints it.
Go
package main import "fmt" func main() { ch := make(chan string) go func() { ch <- "Hi from goroutine" }() msg := <-ch fmt.Println(msg) }
OutputSuccess
Important Notes
Always make channels before using them with make(chan Type).
Receiving from a channel will wait until there is a value to get.
Sending to a channel will wait until someone is ready to receive, unless the channel is buffered.
Summary
Channels let goroutines send and receive values safely.
Use channel <- value to send and value := <- channel to receive.
This helps your program parts work together without confusion.