]> Cypherpunks.ru repositories - gostls13.git/blob - test/closure.go
delete all uses of panicln by rewriting them using panic or,
[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                         println("want", a[i], "got", n, "at", i)
16                         panic("fail")
17                 }
18         }
19 }
20
21 func f() {
22         var i, j int
23
24         i = 1
25         j = 2
26         f := func() {
27                 c <- i
28                 i = 4
29                 g := func() {
30                         c <- i
31                         c <- j
32                 }
33                 g()
34                 c <- i
35         }
36         j = 5
37         f()
38 }
39
40 // Accumulator generator
41 func accum(n int) func(int) int {
42         return func(i int) int {
43                 n += i
44                 return n
45         }
46 }
47
48 func g(a, b func(int) int) {
49         c <- a(2)
50         c <- b(3)
51         c <- a(4)
52         c <- b(5)
53 }
54
55 func h() {
56         var x8 byte = 100
57         var x64 int64 = 200
58
59         c <- int(x8)
60         c <- int(x64)
61         f := func(z int) {
62                 g := func() {
63                         c <- int(x8)
64                         c <- int(x64)
65                         c <- z
66                 }
67                 g()
68                 c <- int(x8)
69                 c <- int(x64)
70                 c <- int(z)
71         }
72         x8 = 101
73         x64 = 201
74         f(500)
75 }
76
77 func newfunc() func(int) int { return func(x int) int { return x } }
78
79
80 func main() {
81         go f()
82         check([]int{1, 4, 5, 4})
83
84         a := accum(0)
85         b := accum(1)
86         go g(a, b)
87         check([]int{2, 4, 6, 9})
88
89         go h()
90         check([]int{100, 200, 101, 201, 500, 101, 201, 500})
91
92         x, y := newfunc(), newfunc()
93         if x == y {
94                 println("newfunc returned same func")
95                 panic("fail")
96         }
97         if x(1) != 1 || y(2) != 2 {
98                 println("newfunc returned broken funcs")
99                 panic("fail")
100         }
101 }