-
Notifications
You must be signed in to change notification settings - Fork 2
/
channel_select_statement.go
49 lines (41 loc) · 1.02 KB
/
channel_select_statement.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Select statement is specifically desgined for channels.
// In select statement, no predetermined order unlike switch statement (case 1 is match then rest will not be perform).
// In select statement multiple cases can be perform at the same time.
// Select statement is specifically desgined for and have the current go routine pause until one of those channels is either ready to send a messsage or receive a message for the use case.
// If any one of the case is not execute then default(non-block) will be execute.
/* Syntax
select {
case 1:
# code block
case 2:
# code block
default:
# use default case for non-blocking select
}
*/
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
ch2 <- "Message 2"
time.Sleep(10 * time.Second)
}()
go func() {
ch1 <- "Message 1"
}()
for i := 0; i < 2; i++ {
select {
case r1 := <-ch1:
fmt.Println(r1)
case r2 := <-ch2:
fmt.Println(r2)
default:
fmt.Println("No message describe.")
}
}
}