惜风不起、唯有努力!
golang 管道的简单使用

golang 管道的简单使用

package main

import (
	"fmt"
)

var (
	//声明并初始化一个整数管道
	intchan = make(chan int, 3)
	mapchan = make(chan map[string]string, 2)
	//intList = make([] int, 0)
	intslice = []int{10, 20, 30}
	num01    int
)

type Dog struct {
	name string
	age  int
}

func intChanRW() {
	//管道写
	for _, v := range intslice {
		intchan <- v
	}
	//统计管道内值有多少个
	fmt.Printf("chan value--> %d, chan cap--> %d\n", len(intchan), cap(intchan))

	//管道读,管道是按照先进先出的顺序来的,跟栈的顺序是反的。
	num01 = <-intchan
	//正常返回是10
	fmt.Println(num01)
	//再次查看管道值数量多少。
	fmt.Printf("chan value--> %d, chan cap--> %d\n", len(intchan), cap(intchan))
	//再次循环
	var chanSlice []int
	chanSlice = make([]int, 0)
	countChan := len(intchan)
	//管道数据读取后,添加至切片
	for i := 1; i <= countChan; i++ {
		chanSlice = append(chanSlice, <-intchan)
	}
	fmt.Println(chanSlice)
	fmt.Printf("chan value--> %d, chan cap--> %d\n", len(intchan), cap(intchan))
}

func mapChanRW() {
	//伪map数据结构
	map1 := make(map[string]string, 2)
	map2 := make(map[string]string, 2)
	map1["name"] = "tom"
	map1["home"] = "beijing"
	map2["name"] = "xm"
	map2["home"] = "shanghai"
	//把map写入管道
	mapchan <- map1;
	mapchan <- map2
	fmt.Printf("mapchan value--> %d\n", len(mapchan))
	//取出跟intchan一样
	//......
}

func stuBlChanRW() {
	stuBlchan := make(chan Dog, 10)
	dog01 := Dog{"xf", 3}
	stuBlchan <- dog01
	fmt.Println("=================")
	var s Dog
	s = <-stuBlchan
	fmt.Println(s.name, s.age)
}

func main() {
	intChanRW()
	mapChanRW()
	stuBlChanRW()
}

遍历和关闭

package main

import "fmt"

func clo()  {
	strchan := make(chan string, 3)
	strchan <- "aa"; strchan <- "bb"
	//关闭管道后是不能写的,只能读
	close(strchan)
	//写报错
	//strchan <- "aa"
	//读可以
	s := <- strchan
	fmt.Println(s)

}

func forc()  {
	intChan := make(chan int, 100)
	for i:=1; i<=100; i++{
		intChan <- i * 3
	}
	close(intChan)
	for v := range intChan{
		fmt.Printf("chan value --> %d\n", v)
	}
}

func main() {
	clo()
	forc()
}

发表回复

您的电子邮箱地址不会被公开。