• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Go-select和switch的使用区别

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
go中string是如何实现的呢发布时间:2022-07-10
下一篇:
Errorresponsefromdaemon:ociruntimeerror:container_linux.go:235:startingcontainer ...发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap