go anonymous function

前端之家收集整理的这篇文章主要介绍了go anonymous function前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

package main

import "fmt"

// function add
func add(a,b int) int {
return a + b
}

// 1
func testFunc1() {

  1. // function "add" to var "f1"
  2. // then "f1" is a function
  3. f1 := add
  4.  
  5. // type of f1 = func(int int) int
  6. fmt.Printf("type of f1 = %T\n",f1)
  7.  
  8. // call function "f1"
  9. // params are 2 and 5
  10. sum := f1(2,5)
  11.  
  12. // sum = 7
  13. fmt.Printf("sum = %d\n",sum)

}

// 2
func testFunc2() {

  1. // anonymous function to var "f1",then "f1" is a function
  2. f1 := func(a,b int) int {
  3. return a + b
  4. }
  5.  
  6. // type of f1 = function(int,int) int
  7. fmt.Printf("type of f1 = %T\n",f1)
  8.  
  9. // call function f1,params are 2 and 5
  10. sum := f1(2,sum)

}

// 3
func testFunc3() {
var i = 0

  1. // the statement after "defer" will be pushed into stack first
  2. // so the value of var "i" will be "0"
  3. // defer i = 0
  4. defer fmt.Printf("defer i = %d\n",i)
  5.  
  6. i = 100
  7.  
  8. // i = 100
  9. fmt.Printf("i = %d\n",i)
  10.  
  11. return

}

// 4
func testFunc4() {
var i = 0

  1. // the anonymous function after "defer" will be pushed into stack first
  2. // but at this time,the statement in function will not be pushed into stack
  3. // so at this time the value of var "i" is not specific
  4. // the value of var
  5. // at the end the value of var "i" is 100
  6. defer func() {
  7. fmt.Printf("defer i = %d\n",i)
  8. }()
  9.  
  10. i = 100
  11.  
  12. // i = 100
  13. fmt.Printf("i = %d\n",i)
  14.  
  15. return

}

func main() {//testFunc1()//testFunc2()//testFunc3()testFunc4()}

猜你在找的Go相关文章