]> Cypherpunks.ru repositories - gostls13.git/blob - test/range.go
range over channels.
[gostls13.git] / test / range.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 // test range over channels
10
11 func gen(c chan int, lo, hi int) {
12         for i := lo; i <= hi; i++ {
13                 c <- i;
14         }
15         close(c);
16 }
17
18 func seq(lo, hi int) chan int {
19         c := make(chan int);
20         go gen(c, lo, hi);
21         return c;
22 }
23
24 func testchan() {
25         s := "";
26         for i := range seq('a', 'z') {
27                 s += string(i);
28         }
29         if s != "abcdefghijklmnopqrstuvwxyz" {
30                 panicln("Wanted lowercase alphabet; got", s);
31         }
32 }
33
34 // test that range over array only evaluates
35 // the expression after "range" once.
36
37 var nmake = 0;
38 func makearray() []int {
39         nmake++;
40         return []int{1,2,3,4,5};
41 }
42
43 func testarray() {
44         s := 0;
45         for k, v := range makearray() {
46                 s += v;
47         }
48         if nmake != 1 {
49                 panicln("range called makearray", nmake, "times");
50         }
51         if s != 15 {
52                 panicln("wrong sum ranging over makearray");
53         }
54 }
55
56 func main() {
57         testchan();
58         testarray();
59 }