Go - chiusura della funzione

Il linguaggio di programmazione Go supporta funzioni anonime che possono agire come chiusure di funzioni. Le funzioni anonime vengono utilizzate quando si desidera definire una funzione inline senza passarle alcun nome.

Nel nostro esempio, abbiamo creato una funzione getSequence () che restituisce un'altra funzione. Lo scopo di questa funzione è chiudere su una variabile i di funzione superiore per formare una chiusura. Ad esempio:

package main

import "fmt"

func getSequence() func() int {
   i:=0
   return func() int {
      i+=1
      return i  
   }
}

func main(){
   /* nextNumber is now a function with i as 0 */
   nextNumber := getSequence()  

   /* invoke nextNumber to increase i by 1 and return the same */
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   
   /* create a new sequence and see the result, i is 0 again*/
   nextNumber1 := getSequence()  
   fmt.Println(nextNumber1())
   fmt.Println(nextNumber1())
}

Quando il codice precedente viene compilato ed eseguito, produce il seguente risultato:

1
2
3
1
2