blob: 8bb516d29cadaaf2052d772cd34bb0eb6d2641d5 [file] [log] [blame]
Russ Cox0f4f2a62009-02-06 13:46:56 -08001// $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
7package main
8
9var c = make(chan int);
10
11func 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
20func 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
40func accum(n int) (func(int) int) {
41 return func(i int) int {
42 n += i;
43 return n;
44 }
45}
46
47func g(a, b func(int) int) {
48 c <- a(2);
49 c <- b(3);
50 c <- a(4);
51 c <- b(5);
52}
53
54func 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
Russ Cox9346c6d2009-07-28 20:01:00 -070076func newfunc() (func(int) int) {
77 return func(x int) int { return x }
78}
79
Russ Cox0f4f2a62009-02-06 13:46:56 -080080
81func main() {
82 go f();
Russ Coxbe2edb52009-03-03 08:39:12 -080083 check([]int{1,4,5,4});
Russ Cox0f4f2a62009-02-06 13:46:56 -080084
85 a := accum(0);
86 b := accum(1);
87 go g(a, b);
Russ Coxbe2edb52009-03-03 08:39:12 -080088 check([]int{2,4,6,9});
Russ Cox0f4f2a62009-02-06 13:46:56 -080089
90 go h();
Russ Coxbe2edb52009-03-03 08:39:12 -080091 check([]int{100,200,101,201,500,101,201,500});
Russ Cox9346c6d2009-07-28 20:01:00 -070092
93 x, y := newfunc(), newfunc();
94 if x == y {
95 panicln("newfunc returned same func");
96 }
97 if x(1) != 1 || y(2) != 2 {
98 panicln("newfunc returned broken funcs");
99 }
Russ Cox0f4f2a62009-02-06 13:46:56 -0800100}