Go基础之For循环

package main

import "fmt"

func main() {
	fmt.Println("For_Simple:\n")
	For_Simple()
	fmt.Println("For_Ever:\n")
	For_Ever()
	fmt.Println("For_Break_One:\n")
	For_Break_One()
	fmt.Println("For_Break_Any:\n")
	For_Break_Any()
}

func For_Simple() {
	//标准For循环,注意表达式不带花括号
	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	}
	fmt.Println("For_Simple:sum =", sum)
}

func For_Ever() {
	//无限循环,后不跟表达式
	sum := 0
	for {
		sum += 2
		if sum > 100 {
			break
		}
	}
	fmt.Println("For_Ever:sum =", sum)
}

func For_Break_One() {
	//break默认跳出本次循环,就近原则
	for i := 0; i < 3; i++ {
		for j := 0; j < 3; j++ {
			if j == 2 {
				break
			}
			fmt.Printf("i = %d,j = %d\n", i, j)
		}
	}
}

func For_Break_Any() {
	//break后跟定义好的标志,可以指定跳跃
JumpTo:
	for i := 0; i < 3; i++ {
		for j := 0; j < 3; j++ {
			if j == 2 {
				break JumpTo
			}
			fmt.Printf("i = %d,j = %d\n", i, j)
		}
	}
}

你可能感兴趣的:(Go)