]> Cypherpunks.ru repositories - gostls13.git/blob - test/closure.go
closures - runtime and debugger support, test case
[gostls13.git] / test / closure.go
1 // $G $D/$F.go && $L $F.$A && ./$A.out
2
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 package main
8
9 var c = make(chan int);
10
11 func check(a []int) {
12         for i := 0; i < len(a); i++ {
13                 n := <-c;
14                 if n != a[i] {
15                         panicln("want", a[i], "got", n, "at", i);
16                 }
17         }
18 }
19
20 func f() {
21         var i, j int;
22
23         i = 1;
24         j = 2;
25         f := func() {
26                 c <- i;
27                 i = 4;
28                 g := func() {
29                         c <- i;
30                         c <- j;
31                 };
32                 g();
33                 c <- i;
34         };
35         j = 5;
36         f();
37 }
38
39 // Accumulator generator
40 func accum(n int) (func(int) int) {
41         return func(i int) int {
42                 n += i;
43                 return n;
44         }
45 }
46
47 func g(a, b func(int) int) {
48         c <- a(2);
49         c <- b(3);
50         c <- a(4);
51         c <- b(5);
52 }
53
54 func h() {
55         var x8 byte = 100;
56         var x64 int64 = 200;
57
58         c <- int(x8);
59         c <- int(x64);
60         f := func(z int) {
61                 g := func() {
62                         c <- int(x8);
63                         c <- int(x64);
64                         c <- z;
65                 };
66                 g();
67                 c <- int(x8);
68                 c <- int(x64);
69                 c <- int(z);
70         };
71         x8 = 101;
72         x64 = 201;
73         f(500);
74 }
75
76
77 func main() {
78         go f();
79         check([]int{1,4,5,4});
80
81         a := accum(0);
82         b := accum(1);
83         go g(a, b);
84         check([]int{2,4,6,9});
85
86         go h();
87         check([]int{100,200,101,201,500,101,201,500});
88 }