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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,106 questions

40,778 answers

573 users

How to use anonymous functions (closure) in Go

Learn & Practice SQL


144 views
asked Feb 24, 2020 by avibootz
edited Feb 27, 2020 by avibootz

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 110 views
2 answers 1,168 views
4 answers 61 views
61 views asked Jun 10, 2023 by avibootz
1 answer 30 views
30 views asked Jun 9, 2023 by avibootz
...