-
Notifications
You must be signed in to change notification settings - Fork 21
/
channel2.go
57 lines (49 loc) · 1.03 KB
/
channel2.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
50
51
52
53
54
55
56
57
//
// Demonstrates an untyped channel that receives multiple types
//
// Run with "go run channel2.go"
//
package main
import (
"fmt"
"math"
)
type Org struct {
id int16
name string
}
func main() {
fmt.Println("--- channel ---")
// Build the channel
c := make(chan interface{})
// A go routine that sends to the channel
go fillChannel(c)
// Read from the channel
for value := range c {
switch str := value.(type) {
case string:
fmt.Printf("string: %s\n", str)
case Org:
fmt.Printf("org: %s\n", str.name)
default:
fmt.Println("Oops, not a string or an Org")
}
}
//x := <-c
//fmt.Printf("id:%d, name: %s \n", x.id, x.name)
//x = <-c
//fmt.Printf("id:%d, name: %s \n", x.id, x.name)
}
func fillChannel(c chan<- interface{}) {
for i := 0; i < 8; i++ {
org := Org{id: int16(i), name: fmt.Sprintf("org%d", i)}
if math.Mod(float64(i), float64(2)) == 0 {
c <- org
} else {
c <- org.name
}
}
// Tell the receiver that we're done sending
close(c)
}
// =================================================