Source file test/for.go

     1  // run
     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  // Test for loops.
     8  
     9  package main
    10  
    11  func assertequal(is, shouldbe int, msg string) {
    12  	if is != shouldbe {
    13  		print("assertion fail", msg, "\n")
    14  		panic(1)
    15  	}
    16  }
    17  
    18  func main() {
    19  	var i, sum int
    20  
    21  	i = 0
    22  	for {
    23  		i = i + 1
    24  		if i > 5 {
    25  			break
    26  		}
    27  	}
    28  	assertequal(i, 6, "break")
    29  
    30  	sum = 0
    31  	for i := 0; i <= 10; i++ {
    32  		sum = sum + i
    33  	}
    34  	assertequal(sum, 55, "all three")
    35  
    36  	sum = 0
    37  	for i := 0; i <= 10; {
    38  		sum = sum + i
    39  		i++
    40  	}
    41  	assertequal(sum, 55, "only two")
    42  
    43  	sum = 0
    44  	for sum < 100 {
    45  		sum = sum + 9
    46  	}
    47  	assertequal(sum, 99+9, "only one")
    48  
    49  	sum = 0
    50  	for i := 0; i <= 10; i++ {
    51  		if i%2 == 0 {
    52  			continue
    53  		}
    54  		sum = sum + i
    55  	}
    56  	assertequal(sum, 1+3+5+7+9, "continue")
    57  
    58  	i = 0
    59  	for i = range [5]struct{}{} {
    60  	}
    61  	assertequal(i, 4, " incorrect index value after range loop")
    62  
    63  	i = 0
    64  	var a1 [5]struct{}
    65  	for i = range a1 {
    66  		a1[i] = struct{}{}
    67  	}
    68  	assertequal(i, 4, " incorrect index value after array with zero size elem range clear")
    69  
    70  	i = 0
    71  	var a2 [5]int
    72  	for i = range a2 {
    73  		a2[i] = 0
    74  	}
    75  	assertequal(i, 4, " incorrect index value after array range clear")
    76  }
    77  

View as plain text