Go-day01

Go-实现hello_world

package main

import "fmt"

func main() {
	fmt.Println("hello world!")
}

GO-goroute并发

package main

import (
	"fmt"
	"time"
)

func test_goroute(a int ,b int){
	sum := a + b
	fmt.Println(sum)
}

func main() {
	for i := 0 ; i < 100 ; i ++ {
	  go test_goroute(200,100)
	}
	time.Sleep(2 *time.Second)
}

Go-管道channel

  相似unix/linux的pipe
  多个goroute之间经过channel通讯
  支持任何类型
  func main(){
  pipe := make(chan int,3) //chan 管道 3表明管道的大小
  pipe <- 1
  pipe <- 2python

  }linux

  csp模型(Communication Sequential project) goroute+channel并发

  全局变量也能够作,可是不建议使用函数

package main

import (
	"fmt"
	//"time"
)

func test_pipe(){
	//建立一个大小为3的管道
	pipe := make(chan int,3)
	pipe <- 1
	pipe <- 2
	pipe <- 3
	var t1 int
	t1 = <- pipe //管道先进先出
	pipe <- 4
	fmt.Println(t1)
	fmt.Println(len(pipe))
}

func main() {
	test_pipe()
	//time.Sleep(1 *time.Second)
}

/*
当放入的数据大于管道大小会编译的时候会产生死锁

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.test_pipe()
	C:/Users/liujiliang/PycharmProjects/firstgo/hello.go:14 +0xae
main.main()
	C:/Users/liujiliang/PycharmProjects/firstgo/hello.go:19 +0x27
exit status 2
*/

 gofmt

当出现代码格式特别乱 能够经过gofmt -w test.go ui

goroute&channel应用

 当channel里没put值的时候,取管道数据默认会阻塞住编码

package main

import "fmt"
import "time"

var pipe chan int

func add_sum(a int,b int ) {
	sum := a + b
	time.Sleep(3 * time.Second)
	pipe <- sum


}

func main() {
	pipe = make(chan int ,1)
	go add_sum(1,2)
	c :=<- pipe
	fmt.Println("num=" ,c)
}

// 3秒后打印3

Go的多返回值

package main

import "fmt"

func calc(a int,b int) (int,int){
	c := a + b
	d := (a + b)/2
	return c, d
}

func main() {
	//sum,avg := calc(10,5) //多个返回值
	sum,_ := calc(100,200) //多个返回值 其中一个不用,采用下划线占位
	//fmt.Println("sum=",sum,"avg=",avg)
	fmt.Println("sum=",sum)


}   
 

Go包的概念

  Go的编码都是utf-8
  1.和python同样,把相同功能的代码放到同一个目录,称之为包
  2.包能够被其余包引用
  3.main包是用来生成可执行文件,每一个程序只有一个main包
  4.包的主要用途是提升代码的可复用性spa

 

Go练习用goroute打印0-99

  goroute和主线程一块儿运行线程

package main

import (
	"fmt"
	"time"
)

func test_goroute(a int){
	fmt.Println(a)
}

func main() {
	for i := 0 ; i < 100 ; i ++ {
	  go test_goroute(i)
	}
	time.Sleep(3 *time.Second)
}

  

  go build xxx/main -o /bin/test #生成go文件到bin下
go 编译,有main函数的话 编译后是可执行文件,没有main函数 编译后是lib库
本站公众号
   欢迎关注本站公众号,获取更多信息