Golang学习笔记二

判断语句

Posted by CDz on January 13, 2019

if语句

  • if语言demo,可以看出 if语句后条件不需要加()
/**
if语言demo,可以看出 if语句后条件不需要加()
*/
func ifDemo() {

	const filename = "adc.txt"

	bytes, e := ioutil.ReadFile(filename) //golang返回值可以是多个,需要多个值来接收

	if e != nil {
		fmt.Println(e)
	} else {
		fmt.Printf("%s\n", bytes)
	}

	if file, i := ioutil.ReadFile(filename); i != nil { //另一种写法,if语句中是可以跟多个语句,必须使用;分号隔开,条件中可以赋值
		fmt.Println(e)
	} else {
		fmt.Printf("%s/n", file)
	}

}

switch用法

  • switch后可以没有表达式
  • switch用法,不需要添加 break,会自动返回

/**
switch用法,不需要添加 break,会自动返回
switch后可以没有表达式
*/
func switchDemo() {
	fmt.Print(grade(81), grade(20), grade(100), grade(90))
}

func grade(soure int) string {

	g := ""
	switch {
	case soure < 60:
		g = "F"
	case soure < 80:
		g = "D"
	case soure < 90:
		g = "B"
	case soure <= 100:
		g = "A"
	case soure < 0 || soure > 100:
		panic(fmt.Sprintf("Wrong score: %d", soure))
	}
	return g
}

循环语句for

  • for条件不需要括号
  • for可以省略初始条件,递增条件,判断条件

正常的for循环使用


/**
正常的for循环使用

- for条件不需要括号
- for可以省略初始条件,递增条件,判断条件
*/
func forDemo() {
	sum := 0
	for i := 0; i <= 100; i++ {
		sum += i
	}
	println(sum)
}

for可以没有初始条件

/**
	- for可以没有初始条件

转换二进制
	一个(n)十进制的数转换为2进制 步骤
			n / 2 得到的数字 % 2 所得到的数字 向前放置
			当 n / 2 为0时结束
*/
func convert2Bin(n int) string {

	bin := ""
	for ; n > 0; n /= 2 {
		bin = strconv.Itoa(n%2) + bin
	}
	return bin
}

for只有判断条件

  • 相当于while语句
/**
读取文件时
	使用os.open(string文件名)打开一个文件
	然后通过bufio.NewScanner(file) 生成一个文件的扫描
	for只有一个判断语言,就能类似与 while循环语言 ,
	值得一提的是golang中没有while语句
*/
func printFile(filename string) {

	file, e := os.Open(filename)

	if e != nil {
		panic(e)
	}

	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		println(scanner.Text())
	}

}

for没有条件–相当于死循环

  • Golang中没有while语句
  • 死循环直接使用for不加任何条件

/**
对于死循环来说,
	golang有更加简洁的写法
	直接使用for不加条件,就是死循环
	相比java -> 死循环 for(;;) 或者用的最多的 while(true)  会更加简洁
*/
func forever() {
	for {
		println("a")
	}
}

总结

  • 总结for
    • 忽略初始条,相当于while
    • 死循环直接使用for {} (后面什么条件也不加)
  • 基本语法
    • for,if后面条件语句不需要括号
    • if条件里也可以定义变量
    • 没有while
    • switch不需要break

作者所有的学习源码在 go学习源码github地址,如果觉得有用的话帮小智贡献一个star😁