Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to use anonymous functions (closure) in Go

2 Answers

0 votes
package main

import (  
    "fmt"
)

func get_num() func() int {
    n := 0
    return func() int {
        n++
        return n
    }
}
func main() {  
     f := get_num()
	 
	 fmt.Println(f())
     fmt.Println(f())
     fmt.Println(f())
	 fmt.Println(f())
	 
	 f2 := get_num()
     fmt.Println(f2())
}
  
  
/*
run:
  
1
2
3
4
1
 
*/

 



answered Feb 24, 2020 by avibootz
0 votes
package main

import "fmt"

func add() func(int) int {
	sum := 0
	return func(n int) int {
		sum += n
		return sum
	}
}

func main() {
	a1, a2 := add(), add()
	for i := 0; i < 10; i++ {
		fmt.Println(a1(i), a2(i * 2))
	}
}


/*
run:

0 0
1 2
3 6
6 12
10 20
15 30
21 42
28 56
36 72
45 90

*/

 



answered Feb 25, 2020 by avibootz

Related questions

1 answer 200 views
2 answers 1,305 views
1 answer 46 views
2 answers 131 views
131 views asked Oct 20, 2020 by avibootz
2 answers 250 views
250 views asked Oct 7, 2020 by avibootz
...