golang reflect.Select 用法
1package main
2
3import (
4 "fmt"
5 "reflect"
6 "strconv"
7)
8
9func main() {
10 var chs1 = make(chan int)
11 var chs2 = make(chan float64)
12 var chs3 = make(chan string)
13 var ch4close = make(chan int)
14 defer close(ch4close)
15
16 go func(c chan int, ch4close chan int) {
17 for i := 0; i < 5; i++ {
18 c <- i
19 }
20 close(c)
21 ch4close <- 1
22 }(chs1, ch4close)
23
24 go func(c chan float64, ch4close chan int) {
25 for i := 0; i < 5; i++ {
26 c <- float64(i) + 0.1
27 }
28 close(c)
29 ch4close <- 1
30 }(chs2, ch4close)
31
32 go func(c chan string, ch4close chan int) {
33 for i := 0; i < 5; i++ {
34 c <- "string:" + strconv.Itoa(i)
35 }
36 close(c)
37 ch4close <- 1
38 }(chs3, ch4close)
39
40
41 var selectCase = make([]reflect.SelectCase, 4)
42 selectCase[0].Dir = reflect.SelectRecv
43 selectCase[0].Chan = reflect.ValueOf(chs1)
44
45 selectCase[1].Dir = reflect.SelectRecv
46 selectCase[1].Chan = reflect.ValueOf(chs2)
47
48 selectCase[2].Dir = reflect.SelectRecv
49 selectCase[2].Chan = reflect.ValueOf(chs3)
50
51 selectCase[3].Dir = reflect.SelectRecv
52 selectCase[3].Chan = reflect.ValueOf(ch4close)
53
54 done := 0
55 finished := 0
56 for finished < len(selectCase)-1 {
57 chosen, recv, recvOk := reflect.Select(selectCase)
58
59 if recvOk {
60 done = done+1
61 switch chosen {
62 case 0:
63 fmt.Println(chosen, recv.Int())
64 case 1:
65 fmt.Println(chosen, recv.Float())
66 case 2:
67 fmt.Println(chosen, recv.String())
68 case 3:
69 finished = finished+1
70 done = done-1
71 // fmt.Println("finished\t", finished)
72 }
73 }
74 }
75 fmt.Println("Done", done)
76
77}
发布日期:2023-04-04 22:48 字数:273 用时
tags:Golang
标签云
alpine(1) api网关(1) async(1) await(1) centos(4) cli(1) client-go(1) debug(1) docker(10) docker-compose(1) dockerfile(1) embed(1) es6(1) etcd(1) etcdctl(1) freemesh(2) git(6) go(5) go-zeus(5) goland(2) golang(7) grafana(2) grpc(5) grpcurl(1) homebrew(1) homedir(1) http(2) hugo(1) java(2) javascript(3) job(1) js(1) json(1) k8s(16) k8s部署指南(1) kubebuilder(1) kubectl(4) kubernetes(1) linux(2) localecompare(1) lombok(1) metrics(2) mock(1) mysql(1) npm(1) nsenter(1) nvm(1) pnpm(2) pprof(1) prettier(1) prometheus(2) protobuf3(1) protoc(1) qiankun(1) request(1) scss(1) servicemesh(1) spring(1) springcloud->freemesh(1) ssh(2) systemctl(1) tcpdump(1) typescript(2) vite(2) vscode(2) vue(8) vue-admin(2) vue3(1) webssh(1) xtermjs(1) xxl-job(1) yarn(1) zookeeper(1) 云原生(4) 云原生框架(1) 介绍(1) 单体架构->freemesh(1) 单元化(1) 博客(1) 压缩(1) 可观测(1) 后台管理系统(1) 命名规范(1) 多云多活(1) 如水网(1) 安全(1) 安装(1) 容器(2) 开发联调神器(1) 微前端(1) 微服务(2) 微服务架构->freemesh(1) 微服务框架(1) 快速开始(1) 控制面(1) 数据面(1) 文集(2) 服务发现(1) 服务网格(1) 流量泳道(1) 流量管理(1) 监控告警(1) 端口映射(1) 证书(1) 负载均衡(1) 配置(1)