其他分享
首页 > 其他分享> > Go-channel

Go-channel

作者:互联网

channel管道

image

package main

import "fmt"

func main() {
	intChan := make(chan int, 3)
	fmt.Printf("intChan的值%v intChan本身的地址%p\n", intChan, &intChan)
	intChan <- 10
	num := 211
	intChan <- num
	fmt.Printf("len=%v cap=%v\n", len(intChan), cap(intChan))
	num2 := <-intChan
	fmt.Printf("num2=%v\n", num2)
	fmt.Printf("len=%v cap=%v\n", len(intChan), cap(intChan))
}

image

放任意类型的空接口(类型断言)

package main

import "fmt"

type Cat struct {
	Name string
	Age  int
}

func main() {
	allChan := make(chan interface{}, 3)
	allChan <- 10
	allChan <- "tom jack"
	cat := Cat{"小花猫", 4}
	allChan <- cat
	<-allChan
	<-allChan
	newCat := <-allChan
	fmt.Printf("newCat=%T,newCat=%v\n", newCat, newCat)
	a := newCat.(Cat)
	fmt.Printf("newCat.Name=%v\n", a.Name)
}

image

channel的遍历和关闭

package main

import "fmt"

func main() {
	intChan := make(chan int, 100)
	for i := 0; i < 100; i++ {
		intChan <- i * 2
	}
	close(intChan)
	for v := range intChan {
		fmt.Println("v=", v)
	}
}

image

goroutine和channel结合

image

image

package main

import "fmt"

func writeData(intChan chan int) {
	for i := 1; i <= 50; i++ {
		intChan <- i
		fmt.Println("写入数据", i)
	}
	close(intChan)
}

func readData(intChan chan int, exitChan chan bool) {
	for {
		v, ok := <-intChan
		if !ok {
			break
		}
		fmt.Printf("读到数据=%v\n", v)
	}
	exitChan <- true
	close(exitChan)
}

func main() {
	intChan := make(chan int, 50)
	exitChan := make(chan bool, 1)
	go writeData(intChan)
	go readData(intChan, exitChan)
	for {
		_, ok := <-exitChan
		if !ok {
			break
		}
	}
}

image

标签:intChan,fmt,chan,int,Go,import,main,channel
来源: https://www.cnblogs.com/jgg54335/p/15856462.html