go 管道的使用

1, 管道创建

package main

import "fmt"

func testPipe() {
	// 创建一个管道
	pipe := make(chan int, 3)
	// 将数据放入管道中
	pipe <- 1
	pipe <- 2
	// 查看管道中数据量
	fmt.Println("pipe size:", len(pipe))
	pipe <- 3
	fmt.Println("pipe size:", len(pipe))
	// 从管道中取出数据
	val := <- pipe
	fmt.Println("val:", val)

	val = <- pipe
	fmt.Println("val:", val)
	val = <- pipe
	fmt.Println("val:", val)
}

func main() {
	testPipe()
}

2,在函数中使用管道之全局变量方式

package main

import "fmt"

/* 在函数中使用管道之全局变量方式 */

var pipe chan int

func add1(a int, b int) {
	sum := a + b
	pipe <- sum
}

func main() {
	pipe = make(chan int, 3)
	go add1(39, 230)
	sum := <- pipe
	fmt.Println("sum =", sum)
}

3,在函数中使用管道之传入参数方式

package main

import "fmt"

/* 在函数中使用管道之传入参数方式 */

func add2(a int, b int, pipe1 chan int) {
	sum := a + b
	pipe1 <- sum
}

func main() {
	var pipe chan int
	pipe = make(chan int, 3)
	add2(20, 34, pipe)
	sum := <- pipe
	fmt.Println("sum =", sum)
}
posted @ 2022-02-26 22:48  ty1539  阅读(191)  评论(0编辑  收藏  举报