默认情况下,管道式双向的
可读可写 var chan1 chan int
只读 var chan2 <-chan int
只写 var chan3 chan<- int
func main() {
var intChan chan int
intChan = make(chan int, 3)
fmt.Printf("intChan 的值=%v intChan 本身的地址=%p\n", intChan, &intChan)
intChan<- 10
num := 211
intChan<- num
intChan<- 50
fmt.Printf("channel len= %v cap=%v \n", len(intChan), cap(intChan))
var num2 int
num2 = <-intChan
fmt.Println("num2=", num2)
fmt.Printf("channel len= %v cap=%v \n", len(intChan), cap(intChan))
num3 := <-intChan
num4 := <-intChan
num5 := <-intChan
fmt.Println("num3=", num3, "num4=", num4, "num5=", num5)
}
var mapChan chan map[string]string
mapChan = make(chan map[string]string, 10)
m1 := make(map[string]string, 20)
m1["city1"] = "北京"
m1["city2"] = "天津"
m2 := make(map[string]string, 20)
m2["city1"] = "北京1"
m2["city2"] = "天津1"
mapChan <- m1
mapChan <- m2
fmt.Println(<-mapChan)
fmt.Println(<-mapChan)
>存放10个任意类型变量
var allChan chan interface{}
allChan = make(chan interface{}, 10)
cat1 := Cat{Name:"tom", Age: 10}
allChan<-cat1
allChan<-cat2
allChan<-10
allChan<-"jack"
明白了吗,chan 必须make后再使用,值类型必须是chan后面定义的类型,如果多种类型就使用interface{},泛型