Go语言入门到实战——05Go语言里条件和循环

Go语言入门到实战——00主目录
上一章我们讲解了Go语言里的运算符,这一章我们开始讲解条件和循环。
1.循环
Go语言相比于其他语言,循环它只支持for循环。

//普通的for循环,不用括号包起来
func TestWhile(t *testing.T) {
    
    
	for i := 1; i <= 5; i++ {
    
    
		t.Log(i)
	}
}

在这里插入图片描述

//while(n<5)的go表示法
func TestWhile(t *testing.T) {
    
    
	var n int = 0
	for n < 5 {
    
    
		t.Log(n)
		n++
	}
}

在这里插入图片描述

//while无限循环的go表示方法
func TestWhile(t *testing.T) {
    
    
	var n int = 0
	for {
    
    
		t.Log(n)
		n++
		if n > 10 {
    
    
			break
		}
	}
}

在这里插入图片描述
2.if条件

if condition{
    
    
	......
}else{
    
    
	......
}
if condition-1{
    
    
	......
}else if condition-2{
    
    
	......
}else{
    
    
	......
}

go语言的条件语句和主流的语言的区别在于:

1.condition都是bool表达式的值必须是bool2.支持变量赋值

这里给出支持变量赋值的例子

func TestCondition(t *testing.T) {
    
    
	//把判断值赋值给变量,然后让变量作为condition值去进行判断
	if a := 1 == 1; a {
    
    
		t.Log(a)
	}
}

在这里插入图片描述
当然一般这种方式常用的使用方法形式如下:

func TestCondition(t *testing.T) {
    
    
	//val是函数返回值,err是错误返回
	if val,err = Func();err==nil{
    
    
		......
	}else{
    
    
		......
	}
}

3.switch条件
switch我们主要看两种写法
3.1 写法1

package main

import "fmt"

func main() {
    
    
	var a int = 20
	switch a {
    
    
	case 1:
		fmt.Print(1)
	case 2:
		fmt.Print(2)
	case 3:
		fmt.Print(3)
	case 20:
		fmt.Print(20)
	case 21:
		fmt.Print(21)
	default:
		fmt.Print("others")
	}
}

在这里插入图片描述
3.2 写法2

//这种写法可以直接看作是if else语句
package main
import "fmt"
func main() {
    
    
	switch {
    
    
	case 1 > 2:
		fmt.Print(1)
	case 2 > 3:
		fmt.Print(2)
	case 3 < 4:
		fmt.Print(3)
	case 20 < 21:
		fmt.Print(20)
	default:
		fmt.Print("others")
	}
}

在这里插入图片描述
这里给出switch与其他语言的差别所在

1.条件表达式不限制为常量或者整数
2.单个case中可以出现多个结果选项,使用逗号分隔开来
3.go语言不需要使用break来明确退出一个case
4.可以不设定switch后面的表达式,那么这个时候整个switch结构等同于多个if...else语句

上面给的两个例子只体现了3,4两点,下面在给出两个例子来体现1,2

//对应第2点
package typetest

import "testing"

func TestSwich(t *testing.T) {
    
    
	for i := 1; i < 5; i++ {
    
    
		switch i {
    
    
		case 1, 2:
			t.Log("A")
		case 3, 4:
			t.Log("B")
		}
	}
}

在这里插入图片描述

//对应第1点,比如使用string也是可以的
package typetest

import "testing"

func TestSwich(t *testing.T) {
    
    
	var a string = "A"
	switch a {
    
    
	case "A":
		t.Log("A")
	case "B":
		t.Log("B")
	}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44932835/article/details/120889076