Timeouts
This Go code demonstrates the use of the select
statement with time.After
to handle timeouts when waiting for channel communication. Let's go through it with inline comments:
Output
Explanation:
package main
: Indicates that this Go file belongs to the main executable package.import (...)
: Imports necessary packages, including "fmt" for formatting and printing, and "time" for handling time-related operations.func main() { ... }
: The main function, where the execution of the program begins.c1 := make(chan string, 1)
: Creates a buffered channel named 'c1' with a capacity of 1.A goroutine is launched to send "result 1" to 'c1' after a 2-second delay.
The
select
statement is used to either receive a message from 'c1' or timeout after 1 second. If a message is received, it prints the result; otherwise, it prints a timeout message.c2 := make(chan string, 1)
: Creates another buffered channel named 'c2' with a capacity of 1.Another goroutine is launched to send "result 2" to 'c2' after a 2-second delay.
The second
select
statement is used to either receive a message from 'c2' or timeout after 3 seconds. Similarly, it prints the result or a timeout message.
This code demonstrates how the select
statement can be combined with time.After
to handle timeouts when waiting for channel communication. The output will depend on which goroutine completes its work first, and the timeouts are used to handle scenarios where communication takes longer than expected.
Last updated
Was this helpful?