summaryrefslogtreecommitdiff
path: root/test/range.go
blob: 9093d714bc9fa6c457ef1d07022375a2de759c19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// $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" {
		println("Wanted lowercase alphabet; got", s)
		panic("fail")
	}
}

// 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 _, v := range makearray() {
		s += v
	}
	if nmake != 1 {
		println("range called makearray", nmake, "times")
		panic("fail")
	}
	if s != 15 {
		println("wrong sum ranging over makearray")
		panic("fail")
	}
}

// test that range evaluates the index and value expressions
// exactly once per iteration.

var ncalls = 0

func getvar(p *int) *int {
	ncalls++
	return p
}

func testcalls() {
	var i, v int
	si := 0
	sv := 0
	for *getvar(&i), *getvar(&v) = range [2]int{1, 2} {
		si += i
		sv += v
	}
	if ncalls != 4 {
		println("wrong number of calls:", ncalls, "!= 4")
		panic("fail")
	}
	if si != 1 || sv != 3 {
		println("wrong sum in testcalls", si, sv)
		panic("fail")
	}

	ncalls = 0
	for *getvar(&i), *getvar(&v) = range [0]int{} {
		println("loop ran on empty array")
		panic("fail")
	}
	if ncalls != 0 {
		println("wrong number of calls:", ncalls, "!= 0")
		panic("fail")
	}
}

func main() {
	testchan()
	testarray()
	testcalls()
}