ITPub博客

首页 > IT职业 > IT图书 > go anonymous function

go anonymous function

IT图书 作者:wyvernw 时间:2021-09-09 10:11:01 0 删除 编辑

package main

import "fmt"

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

// 1
func testFunc1() {

// function "add" to var "f1"// then "f1" is a functionf1 := add// type of f1 = func(int int) intfmt.Printf("type of f1 = %Tn", f1)// call function "f1"// params are 2 and 5sum := f1(2, 5)// sum = 7fmt.Printf("sum = %dn", sum)

}

// 2
func testFunc2() {

// anonymous function to var "f1", then "f1" is a functionf1 := func(a, b int) int {    return a + b}// type of f1 = function(int, int) intfmt.Printf("type of f1 = %Tn", f1)// call function f1, params are 2 and 5sum := f1(2, 5)// sum = 7fmt.Printf("sum = %dn", sum)

}

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

// the statement after "defer" will be pushed into stack first// so the value of var "i" will be "0"// defer i = 0defer fmt.Printf("defer i = %dn", i)i = 100// i = 100fmt.Printf("i = %dn", i)return

}

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

// the anonymous function after "defer" will be pushed into stack first// but at this time, the statement in function will not be pushed into stack// so at this time the value of var "i" is not specific// the value of var// at the end the value of var "i" is 100defer func() {    fmt.Printf("defer i = %dn", i)}()i = 100// i = 100fmt.Printf("i = %dn", i)return

}

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/835/viewspace-2817721/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-12

  • 博文量
    128
  • 访问量
    1297