Go 学习笔记02.流程控制 for循环/ if-else判断/ swith分支

for 循环

for.go

package main

import "fmt"

func main() {

	// 1.常见的for循环
	i := 1
	for i <= 3 {
		fmt.Println(i)
		i = i + 1
	}

	// 2.经典的写法
	// 初始化条件变量/循环条件/后续执行
	// 经典的初始化/条件/后续形式 `for` 循环。
	for j := 7; j <= 9; j++ {
		fmt.Println(j)
	}

	// 3. 不带条件的for循环
	// 会在内部无限循环,遇到break/return会跳出
	for {
		fmt.Println("loop")
		break
	}
}

if - else

if-else.go

// `if` 和 `else` 分支结构在 Go 中当然是直接了当的了。

package main

import "fmt"

func main() {

	// 1.---------------------------------------------------
	// 这里是一个基本的例子。
	// 判断7是基数odd 还是偶数even
	if 7%2 == 0 {
		// 偶数
		fmt.Println("7 is even")
	} else {
		// 奇数
		fmt.Println("7 is odd")
	}

	// 2.---------------------------------------------------
	// 你可以不要 `else` 只用 `if` 语句。
	if 8%4 == 0 {
		fmt.Println("8 is divisible by 4")
	}

	// 3.---------------------------------------------------
	// 在条件语句之前可以有一个语句;任何在这里声明的变量
	// 都可以在所有的条件分支中使用。
	if num := 9; num < 0 {
		fmt.Println(num, "is negative")
	} else if num < 10 {
		fmt.Println(num, "has 1 digit")
	} else {
		fmt.Println(num, "has multiple digits")
	}
}

// 注意,在 Go 中,你可以不使用圆括号,但是花括号是需要的

switch 分支结构

switch.go

package main

import (
	"fmt"
	"time"
)

func main() {

	// 1. ------------------------------------------------
	// 一个基本的 `switch`
    // 输出 write 2 as two
	i := 2
	fmt.Print("write ", i, " as ")
	switch i {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	case 3:
		fmt.Println("three")
	}
	

	// 2. ------------------------------------------------
	// 比较的值 必须是同类型的
	// default 不是必须的,上面的都匹配不打牌则执行	;
	fmt.Println(time.Now().Weekday())
	switch time.Now().Weekday() {
	case time.Saturday, time.Sunday:
		fmt.Println("in case")
	default:
		fmt.Println("default")
	}

	// 3. ------------------------------------------------
	// 实现if else效果
	// 不带表达式的 `switch` 是实现 if/else 逻辑的另一种方式。
	// 这里展示了 `case` 表达式是如何使用非常量的。
	t := time.Now()
	fmt.Println(t)
	switch {
	case t.Hour() < 12:
		fmt.Println("it's before noon")
	default:
		fmt.Println("it's after noon")
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章