golang基础小记(4)——if、for、for range、switch

if、for、for range、switch

内容均以代码形式呈现,包括:

  1. if,注意表达式不需要加();左大括号{必须与ifelse在同一行;大括号{}绝对不能省去。(示例代码第6行)
  2. for,go中没有while。(示例代码第26行)
  3. for range,遍历数组、切片、字符串时返回索引(int类型)和值;map 返回键和值;通道(channel)只返回通道内的值;如果不想要返回的值,用_代替(示例代码第59行)
  4. switch(示例代码第85行)

示例代码:

package main

import "fmt"

func main() {
	// if
	// if 普通写法
	a := 5
	if a > 10 { // 注意:表达式不需要加小括号; 大括号 { 不能另起一行; 大括号 {} 不可省略
		fmt.Println("a大于10")
	} else if a > 5 {
		fmt.Println("a大于5且小于等于10")
	} else {
		fmt.Println("a小于等于5")
	} // 输出:a小于等于5

	// if特殊写法,可以在 if 表达式前添加一个执行语句
	if b := 7; b > 10 { // 注意作用域,if 中声明的变量只在该 if 中有效
		fmt.Println("b大于10")
	} else if b > 5 {
		fmt.Println("b大于5且小于等于10")
	} else {
		fmt.Println("b小于等于5")
	} // 输出:b大于5且小于等于10

	// for
	// for 普通写法
	for c := 0; c < 5; c++ { // 注意作用域,for 中声明的变量只在该 for 中有效
		fmt.Printf("%d ", c)
	} // 输出:0 1 2 3 4
	fmt.Println()

	// for 省略初始语句
	c := 0
	for ; c < 5; c++ {
		fmt.Printf("%d ", c)
	} // 输出:0 1 2 3 4
	fmt.Println()

	// for 只写中间的条件表达式
	c = 0
	for c < 5 {
		fmt.Printf("%d ", c)
		c++
	} // 输出:0 1 2 3 4
	fmt.Println()

	// for 无限循环, 可以通过 break, goto, return, panic 强制退出循环
	c = 0
	for {
		fmt.Printf("%d ", c)
		c++
		if c >= 5 {
			break
		}
	} // 输出:0 1 2 3 4
	fmt.Println()

	// for range
	// 遍历数组、切片、字符串时返回索引(int)和值
	d := []int{1, 2, 3, 4, 5}
	for i, v := range d {
		fmt.Printf("%d-%d ", i, v)
	} // 输出:0-1 1-2 2-3 3-4 4-5
	fmt.Println()

	// 遍历 map 返回键和值
	m := map[string]int{"a": 1, "b": 2, "c": 3}
	for k, v := range m {
		fmt.Printf("%s-%d ", k, v)
	} // 输出:a-1 b-2 c-3
	fmt.Println()

	// 遍历 channel 只返回通道内的值
	ch := make(chan int, 5)
	for i := 0; i < 5; i++ {
		ch <- 8 * i
	}
	close(ch)
	for data := range ch {
		fmt.Print(data, " ")
	} // 输出:0 8 16 24 32
	fmt.Println()

	// switch
	// 一个分支可以有多个值,每个 switch 只能有一个 default 分支
	e := 5
	switch e { // e 也可以在内部声明,如 switch e := 5; e {}
	case 0:
		fmt.Println("x = 0")
	case 1, 2, 3:
		fmt.Println("x = 1/2/3")
	default:
		fmt.Println("x >= 4")
	} // 输出:x >= 4

	// 分支可以使用表达式,此时需要去掉 switch 语句的判断变量
	f := 5
	switch { // f 也可以在内部声明,如 switch f := 5; {}
	case f < 5:
		fmt.Println("x < 5")
	case f > 5:
		fmt.Println("x > 5")
	default:
		fmt.Println("x = 5")
	} // 输出:x = 5

	// fallthrough 语法可以执行满足条件的 case 的下一个 case(包括 default),是为了兼容 C语言中的 case 设计的。
	g := 2
	switch {
	case g == 1:
		fmt.Print(1)
	case g == 2:
		fmt.Print(2)
		fallthrough
	case g == 3:
		fmt.Print(3)
		fallthrough
	default:
		fmt.Println(4)
	} // 输出:234
}

参考:https://www.liwenzhou.com/posts/Go/04_basic/

猜你喜欢

转载自blog.csdn.net/m0_37710023/article/details/106550359