diff options
author | Russ Cox <rsc@golang.org> | 2009-03-20 11:32:58 -0700 |
---|---|---|
committer | Russ Cox <rsc@golang.org> | 2009-03-20 11:32:58 -0700 |
commit | 1ad77bb12a310a9cafcec6310af6ba88848d719f (patch) | |
tree | ea48563056f767780a96052cd26e853088223652 /test/range.go | |
parent | e904ebc57a0d1dc300f3ecd63e8dbea335a8ecaa (diff) | |
download | go-1ad77bb12a310a9cafcec6310af6ba88848d719f.tar.gz |
range over channels.
also fix multiple-evaluation bug in range over arrays.
R=ken
OCL=26576
CL=26576
Diffstat (limited to 'test/range.go')
-rw-r--r-- | test/range.go | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/test/range.go b/test/range.go new file mode 100644 index 000000000..7a8c68635 --- /dev/null +++ b/test/range.go @@ -0,0 +1,59 @@ +// $G $D/$F.go && $L $F.$A && ./$A.out + +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +// test range over channels + +func gen(c chan int, lo, hi int) { + for i := lo; i <= hi; i++ { + c <- i; + } + close(c); +} + +func seq(lo, hi int) chan int { + c := make(chan int); + go gen(c, lo, hi); + return c; +} + +func testchan() { + s := ""; + for i := range seq('a', 'z') { + s += string(i); + } + if s != "abcdefghijklmnopqrstuvwxyz" { + panicln("Wanted lowercase alphabet; got", s); + } +} + +// test that range over array only evaluates +// the expression after "range" once. + +var nmake = 0; +func makearray() []int { + nmake++; + return []int{1,2,3,4,5}; +} + +func testarray() { + s := 0; + for k, v := range makearray() { + s += v; + } + if nmake != 1 { + panicln("range called makearray", nmake, "times"); + } + if s != 15 { + panicln("wrong sum ranging over makearray"); + } +} + +func main() { + testchan(); + testarray(); +} |