summaryrefslogtreecommitdiff
path: root/src/cmd/vet/test_rangeloop.go
blob: 941fd72aaa73a5c421eb95bf1e4b0155ce4b7c7c (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
// Copyright 2012 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.

// This file contains tests for the rangeloop checker.

// +build vet_test

package main

func RangeLoopTests() {
	var s []int
	for i, v := range s {
		go func() {
			println(i) // ERROR "range variable i enclosed by function"
			println(v) // ERROR "range variable v enclosed by function"
		}()
	}
	for i, v := range s {
		defer func() {
			println(i) // ERROR "range variable i enclosed by function"
			println(v) // ERROR "range variable v enclosed by function"
		}()
	}
	for i := range s {
		go func() {
			println(i) // ERROR "range variable i enclosed by function"
		}()
	}
	for _, v := range s {
		go func() {
			println(v) // ERROR "range variable v enclosed by function"
		}()
	}
	for i, v := range s {
		go func() {
			println(i, v)
		}()
		println("unfortunately, we don't catch the error above because of this statement")
	}
	for i, v := range s {
		go func(i, v int) {
			println(i, v)
		}(i, v)
	}
	for i, v := range s {
		i, v := i, v
		go func() {
			println(i, v)
		}()
	}
	// If the key of the range statement is not an identifier
	// the code should not panic (it used to).
	var x [2]int
	var f int
	for x[0], f = range s {
		go func() {
			_ = f // ERROR "range variable f enclosed by function"
		}()
	}
}