1. Go Language - Initial

A, golang language features

1. Garbage Collection

  • Automatic memory recovery, developers no longer need to manage memory
  • Developers to focus on business implementation, reduce the burden of mental
  • Just need new memory allocation, no release

2. Natural concurrent

  • From the linguistic level support concurrency, very simple
  • goroutine, lightweight threads, create thousands of possible goroutine
  • CSP (Communicating Sequential Process) Model Based [goroutine + pipe]
package main

func test_goroute(a int, b int) int {
    var test_sum int
    test_sum = a + b
    return test_sum
}

func main(){
    go test_goroute(1,2)
}
package main

import "fmt"

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

func main() {
    for i := 1; i < 100; i++ {
        go test_goroute(i)
    }

}

3. Pipeline

  • Pipes, pipe similar to the linux
  • Goroutine between a plurality of communication channel by
  • Support any type
func main() {
    // make开辟一个内存,chan为长度为3整型管道
    pipe := make(chan int, 3)
    // 向管道填值
    pipe <- 2
    pipe <- 2
    pipe <- 2
    fmt.Println(len(pipe))
    var t int
    // 取值
    t =<- pipe
    fmt.Println(t)
}
// 通过管道求和
package main

import (
    "time"
    "fmt"
)

func add(a int, b int, c chan int) {
    sum := a + b
    time.Sleep(3*time.Second)
    c <- sum
}

func main() {
    var pipe chan int
    pipe = make(chan int, 1)
    go add(1,2,pipe)
    sum := <- pipe
    fmt.Println(sum)
}

4. Multi Return value

  • A plurality of function return value
func calc(a int, b int) (int, int){
    sum := a + b
    avg := (a+b)/2
    return sum, avg
}

Guess you like

Origin www.cnblogs.com/hq82/p/11069523.html