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 <- 2

  }

  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 

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.包的主要用途是提高代码的可复用性

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库
 
 
原文地址:https://www.cnblogs.com/liujiliang/p/8981330.html