Home | History | Annotate | Download | only in testdata
      1 // Copyright 2012 The Go Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 // This file contains tests for the rangeloop checker.
      6 
      7 package testdata
      8 
      9 func RangeLoopTests() {
     10 	var s []int
     11 	for i, v := range s {
     12 		go func() {
     13 			println(i) // ERROR "loop variable i captured by func literal"
     14 			println(v) // ERROR "loop variable v captured by func literal"
     15 		}()
     16 	}
     17 	for i, v := range s {
     18 		defer func() {
     19 			println(i) // ERROR "loop variable i captured by func literal"
     20 			println(v) // ERROR "loop variable v captured by func literal"
     21 		}()
     22 	}
     23 	for i := range s {
     24 		go func() {
     25 			println(i) // ERROR "loop variable i captured by func literal"
     26 		}()
     27 	}
     28 	for _, v := range s {
     29 		go func() {
     30 			println(v) // ERROR "loop variable v captured by func literal"
     31 		}()
     32 	}
     33 	for i, v := range s {
     34 		go func() {
     35 			println(i, v)
     36 		}()
     37 		println("unfortunately, we don't catch the error above because of this statement")
     38 	}
     39 	for i, v := range s {
     40 		go func(i, v int) {
     41 			println(i, v)
     42 		}(i, v)
     43 	}
     44 	for i, v := range s {
     45 		i, v := i, v
     46 		go func() {
     47 			println(i, v)
     48 		}()
     49 	}
     50 	// If the key of the range statement is not an identifier
     51 	// the code should not panic (it used to).
     52 	var x [2]int
     53 	var f int
     54 	for x[0], f = range s {
     55 		go func() {
     56 			_ = f // ERROR "loop variable f captured by func literal"
     57 		}()
     58 	}
     59 	type T struct {
     60 		v int
     61 	}
     62 	for _, v := range s {
     63 		go func() {
     64 			_ = T{v: 1}
     65 			_ = []int{v: 1} // ERROR "loop variable v captured by func literal"
     66 		}()
     67 	}
     68 
     69 	// ordinary for-loops
     70 	for i := 0; i < 10; i++ {
     71 		go func() {
     72 			print(i) // ERROR "loop variable i captured by func literal"
     73 		}()
     74 	}
     75 	for i, j := 0, 1; i < 100; i, j = j, i+j {
     76 		go func() {
     77 			print(j) // ERROR "loop variable j captured by func literal"
     78 		}()
     79 	}
     80 	type cons struct {
     81 		car int
     82 		cdr *cons
     83 	}
     84 	var head *cons
     85 	for p := head; p != nil; p = p.next {
     86 		go func() {
     87 			print(p.car) // ERROR "loop variable p captured by func literal"
     88 		}()
     89 	}
     90 }
     91