Go Function Closure Question 1

Introduction

Create makeOddGenerator() function that generates odd numbers:

func makeOddGenerator() func() uint { 
  i := uint(1) 
  return func() (ret uint) { 
    ret = i 
    i += 2 
    return 
  } 
} 

package main /*from ww w. j  a v  a  2s  .  c  o  m*/

import "fmt" 

func makeOddGenerator() func() uint { 
       i := uint(1) 
       return func() (ret uint) { 
         ret = i 
         i += 2 
         return 
       } 
} 
     
func main() { 
   fmt.Println(makeOddGenerator());
   fmt.Println(makeOddGenerator());
   fmt.Println(makeOddGenerator());
}
   



PreviousNext

Related