Source file
test/closure_dynconst.go
1
2
3
4
5
6
7
8
9
10
11 package main
12
13 import "fmt"
14
15 func str(s string) func() string {
16 return func() string { return s }
17 }
18
19 func num(n int) func() int {
20 return func() int { return n }
21 }
22
23 func iface(n int) func() any {
24 return func() any { return n }
25 }
26
27 func nested(s string) func() func() string {
28 return func() func() string {
29 return func() string { return s }
30 }
31 }
32
33 func main() {
34 for i, f := range []func() string{str("a"), str("b"), str("c")} {
35 if got, want := f(), string(rune('a'+i)); got != want {
36 panic(fmt.Sprintf("str: got %q, want %q", got, want))
37 }
38 }
39
40 for i, f := range []func() int{num(0), num(1), num(2)} {
41 if got := f(); got != i {
42 panic(fmt.Sprintf("num: got %d, want %d", got, i))
43 }
44 }
45
46 for i, f := range []func() any{iface(0), iface(1), iface(2)} {
47 if got := f(); got != any(i) {
48 panic(fmt.Sprintf("iface: got %v, want %v", got, i))
49 }
50 }
51
52 for i, f := range []func() func() string{nested("a"), nested("b"), nested("c")} {
53 if got, want := f()(), string(rune('a'+i)); got != want {
54 panic(fmt.Sprintf("nested: got %q, want %q", got, want))
55 }
56 }
57 }
58
View as plain text