Go-select和switch的使用区别

Go-select和switch的使用区别

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "time"
 6 )
 7 
 8 func main() {
 9     i := 2
10     fmt.Print("Write ", i, " as ") //Write 2 as two
11     switch i {
12     case 1:
13         fmt.Println("one")
14     case 2:
15         fmt.Println("two")
16     case 3:
17         fmt.Println("three")
18     }
19 
20     switch time.Now().Weekday() { //It's a weekday
21     case time.Saturday, time.Sunday:
22         fmt.Println("It's the weekend")
23     default:
24         fmt.Println("It's a weekday")
25     }
26 
27     t := time.Now() //It's after noon
28     switch {
29     case t.Hour() < 12:
30         fmt.Println("It's before noon")
31     default:
32         fmt.Println("It's after noon")
33     }
34 
35     whatAmI := func(i interface{}) {
36         switch t := i.(type) {
37         case bool:
38             fmt.Println("I'm a bool")
39         case int:
40             fmt.Println("I'm an int")
41         default:
42             fmt.Printf("Don't know type %T\n", t)
43         }
44     }
45     whatAmI(true)  //I'm a bool
46     whatAmI(1)     //I'm an int
47     whatAmI("hey") //Don't know type string
48 }
49 
50 //select里面的case都满足了,则随机选择一个执行
51 func main02() {
52     c1 := make(chan string)
53     c2 := make(chan string)
54     go func() {
55         time.Sleep(time.Second * 1)
56         c1 <- "one"
57     }()
58     go func() {
59         time.Sleep(time.Second * 2)
60         c2 <- "two"
61     }()
62     for i := 0; i < 2; i++ {
63         select {
64         case msg1 := <-c1:
65             fmt.Println("received", msg1)
66         case msg2 := <-c2:
67             fmt.Println("received", msg2)
68         }
69     }
70 }
71 
72 func main01() {
73     var c1, c2, c3 chan int
74     var i1, i2 int
75 
76     c1 <- 666
77 
78     select {
79     case i1 = <-c1:
80         fmt.Printf("received %d from c1\n", i1)
81     case c2 <- i2:
82         fmt.Printf("sent %d to c2\n", i2)
83     case i3, ok := <-c3: // same as: i3, ok := <-c3
84         if ok {
85             fmt.Printf("received %d from c3\n", i3)
86         } else {
87             fmt.Printf("c3 is closed\n")
88         }
89     default:
90         fmt.Printf("no communication\n")
91     }
92 }
View Code

 

posted @ 2019-05-29 22:35  大西瓜Paul  阅读(562)  评论(0编辑  收藏  举报
/*增加返回顶部按钮*/ 返回顶部 /*给标题增加蓝色背景长条*/