Channels in Go
Go: Channels
Channels are a core feature of concurrency in Go.
Channels provide a way for goroutines to communicate and synchronize with each other by sending and receiving values. Channels are typed, which means that they can only be used to send and receive values of a specific type.
How to createchannels in Go?
In Go, channels are created using the make
function, which takes the type of values that the channel will send and receive as an argument.
Below is an example of how to create a channel of integers:
ch := make(chan int)
Send a value on a channel
To send a value on a channel, we use the <-
operator followed by the value to send
ch <- 42
Receive a value from a channe
To receive a value from a channel, we use the <-
operator on the left side of an
x := <-ch
How to use channels in conjunctions golang
Channels can also be used in conjunction with the "select" statement to wait for multiple channels to become available for sending or receiving. Here's an example:
func main() {
ch1 := make(chan int)
ch2 := make(chan string)
go func() {
ch1 <- 42
}()
go func() {
ch2 <- "hello"
}()
select {
case x := <-ch1:
fmt.Println("received", x)
case s := <-ch2:
fmt.Println("received", s)
}
}
In this example, we create two channels, ch1
and ch2
, and create two goroutines that send values on each channel. We then use the select
statement to wait for either channel to become available for receiving. When a value is received on one of the channels, we print it to the console.
Overall, channels are a powerful tool for synchronizing and communicating between goroutines in Go. By using channels and goroutines together, we can write efficient and safe concurrent programs.
Previous Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go