Russ Cox | 0f4f2a6 | 2009-02-06 13:46:56 -0800 | [diff] [blame] | 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 | |
Russ Cox | 9346c6d | 2009-07-28 20:01:00 -0700 | [diff] [blame] | 76 | func newfunc() (func(int) int) { |
| 77 | return func(x int) int { return x } |
| 78 | } |
| 79 | |
Russ Cox | 0f4f2a6 | 2009-02-06 13:46:56 -0800 | [diff] [blame] | 80 | |
| 81 | func main() { |
| 82 | go f(); |
Russ Cox | be2edb5 | 2009-03-03 08:39:12 -0800 | [diff] [blame] | 83 | check([]int{1,4,5,4}); |
Russ Cox | 0f4f2a6 | 2009-02-06 13:46:56 -0800 | [diff] [blame] | 84 | |
| 85 | a := accum(0); |
| 86 | b := accum(1); |
| 87 | go g(a, b); |
Russ Cox | be2edb5 | 2009-03-03 08:39:12 -0800 | [diff] [blame] | 88 | check([]int{2,4,6,9}); |
Russ Cox | 0f4f2a6 | 2009-02-06 13:46:56 -0800 | [diff] [blame] | 89 | |
| 90 | go h(); |
Russ Cox | be2edb5 | 2009-03-03 08:39:12 -0800 | [diff] [blame] | 91 | check([]int{100,200,101,201,500,101,201,500}); |
Russ Cox | 9346c6d | 2009-07-28 20:01:00 -0700 | [diff] [blame] | 92 | |
| 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 Cox | 0f4f2a6 | 2009-02-06 13:46:56 -0800 | [diff] [blame] | 100 | } |