Go语言条件和循环语句

if 语句

实例:

const filename = "abc.txt"
	contents, err := ioutil.ReadFile(filename)
	if err != nil{
		fmt.Println(err)
	}else {
		fmt.Printf("%s\n", contents)
	}

Go语言中if语句的特殊写法:

可以在if语句后面接;

if contents, err := ioutil.ReadFile(filename); err != nil{
	fmt.Println(err)
}else {
	fmt.Printf("%s\n", contents)
}

switch 语句

Go语言中的switch语句与其他语言不同,默认情况下 case 语句自带 break语句,匹配成功后就不会执行后面的 case语句,如果需要执行后面的 case语句,可以使用 fallthrough

package main

import "fmt"

func grade(score int) string {
	g := ""
	switch  {
	case score < 0 || score >100:
		panic(fmt.Sprintf("Wrong score:%d", score))
	case score < 60:
		g="F"
	case score < 80:
		g = "C"
	case score < 90:
		g = "B"
	case score <=100:
		g = "A"
	//default:
	//	panic(fmt.Sprintf("Wrong score:%d", score))
	}
	return g
}

func main() {
	fmt.Println(grade(70),grade(59),grade(100))
}

switch 语句还可以被用于 type-switch 来判断某个 interface 变量中实际存储的变量类型。

var x interface{}

	switch i := x.(type) {
	case nil:
		fmt.Printf(" x 的类型 :%T",i)
	case int:
		fmt.Printf("x 是 int 型")
	case float64:
		fmt.Printf("x 是 float64 型")
	case func(int) float64:
		fmt.Printf("x 是 func(int) 型")
	case bool, string:
		fmt.Printf("x 是 bool 或 string 型" )
	default:
		fmt.Printf("未知型")
	}

fallthrough

fallthrough会强制执行后面的 case 语句,且它不会去判断下一个 case 的表达式是否为 true。换句话说,fallthrough会无条件的执行它的下一条case语句,不管这条case语句的值是true还是false

实例:

 switch {
    case false:
            fmt.Println("1、case 条件语句为 false")
            fallthrough
    case true:
            fmt.Println("2、case 条件语句为 true")
            fallthrough
    case false:
            fmt.Println("3、case 条件语句为 false")
            fallthrough
    case true:
            fmt.Println("4、case 条件语句为 true")
    case false:
            fmt.Println("5、case 条件语句为 false")
            fallthrough
    default:
            fmt.Println("6、默认 case")
    }

运行结果:

2、case 条件语句为 true
3、case 条件语句为 false
4、case 条件语句为 true

for

  1. for的条件里不需要括号
  2. for的条件里可以省略初始条件,结束条件,递增表达式。

省略初始条件:

package main

import (
	"fmt"
	"strconv"
)

func convertToBin(n int) string{
	result := ""
	for ; n>0; n /=2{
		lsb := n%2
		result = strconv.Itoa(lsb) + result
	}
	return result
}

func main() {
	fmt.Println(convertToBin(5))
}

运行结果:

101

for语句也可以省略初始条件、递增条件。

文件读取:

func readFile(filename string) {
	file, err := os.Open(filename)
	if err != nil{
		// panic用于报错
		panic(err)
	}
	scanner := bufio.NewScanner(file)
	for scanner.Scan(){
		fmt.Println(scanner.Text())
	}
}

如果省略初始条件、条件表达式、递增条件,就相当于死循环。

for{
    // 死循环
    fmt.Println("死循环")
}

Go语言中没有while语句

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值