go语言学习之闭包函数

package main

import (
    "fmt"
)

// 匿名函数1
func intSeq() func() int{
     var arrInt = [10]int{1,2,3,4,5,6,7,8,9,10}
     i := -1
    return func() int{
        i += 1
        return arrInt[i]
    }
}

// 带参数匿名函数2
func intSeq2() func(index int) int{
     var arrInt = [10]int{0,1,2,3,4,5,6,7,8,9}
     i := -1
    return func(index int) int{
        i += 1
        return arrInt[index]
    }
}

 func testIntSeq(){
      nextInt := intSeq()
     fmt.Println(nextInt())
     fmt.Println(nextInt())
 }
 func testIntSeq2(){
      nextInt := intSeq2()
     fmt.Println(nextInt(2))
     fmt.Println(nextInt(5))
 }
 
 
func testQuestion(){
    var j int = 5
    a := func() (func()){
        var i int = 10
        return func() {
            fmt.Println(i, j)
        }
    }
   
    b := a()
    b()
}  
 
 func testQuestion2(){
      var j int = 5
     a := func() (func()){
          var i int = 10
          return func() {
             fmt.Println(i, j)
          }
      }()
     a()
 }

 func Question3() []func() {
      b := make([]func(), 3, 3)
      for i := 0; i < 3; i++ {
          b[i] = func() {
              fmt.Println(i)
          }
      }
       return b
 }  
   // 闭包通过引用的方式使用外部函数的变量。
  // 上例中只调用了一次函数B,构成一个闭包,i 在外部函数B中定义,所以闭包维护该变量 i ,c[0]、c[1]、c[2]中的 i 都是闭包中 i 的引用。
   // 因此执行c:=Question3()后,i 的值已经变为3,故再调用c[0]()时的输出是3而不是0。   
  func testQuestion3(){
  c := Question3()
  c[0]()
  c[1]()
  c[2]()
 }
  
 func Question4() []func() {
    b := make([]func(), 3, 3)
    for i := 0; i < 3; i++ {
        b[i] = (func(j int) func() {
            return func() {
                fmt.Println(j)
            }
        })(i)
    }
    return b
}
 // 通过嵌套匿名函数的方式解决了testQuestion3的问题
 func testQuestion4(){
  c := Question4()
  c[0]()
  c[1]()
  c[2]()
 } 
 func main(){
     // 测试1匿名函数1
     testIntSeq();
     // 测试2带参数匿名函数
     testIntSeq2();
     // 测试3
     testQuestion();
     // 测试4
     testQuestion2();
     
      // 测试5
     testQuestion3();
     // 测试6
     testQuestion4();
 
 }

 

 

posted on 2018-11-13 13:06  奔跑吧,蜗牛!  阅读(282)  评论(0编辑  收藏  举报

导航