
package main
import (
"fmt"
"math/rand"
"time"
)
type
Cat
struct {
Name
string
Age
int
}
func
writeCh(ch
chan
interface{}) {
for
i :=
0; i <
10; i++ {
time.
Sleep(time.Second)
cat := Cat{Name:
randomString(
5), Age:
10}
ch <- cat
fmt.
Printf(
"
%d
进入管道
\n
", i)
}
close(ch)
}
func
readChan(ch
chan
interface{}, done
chan
bool) {
for {
v,
ok := <-ch
if !ok {
break
}
fmt.
Println(
"读协程读入,", v)
}
// for v := range ch {
// fmt.Println(v)
// }
done <-
true
// close(done)
}
func
randomString(length
int)
string {
rand.
Seed(time.
Now().
UnixNano())
b :=
make([]
byte, length)
rand.
Read(b)
return fmt.
Sprintf(
"
%x
", b)[:length]
}
func
main() {
catChan :=
make(
chan
interface{},
10)
done :=
make(
chan
bool)
go
writeCh(catChan)
go
readChan(catChan, done)
<-done
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10972173/viewspace-2917885/
,如需转载,请注明出处,否则将追究法律责任。