目录
一、循环
与其它主流语言的差异:Go语言仅支持关键字 for
注意:Go语言不需要 括号。
1、一个标准的 for 循环的写法
package loop
import (
"fmt"
"testing"
)
func TestStandardForLoop(t *testing.T) {
for j := 0; j < 10; j++{
//.....
fmt.Println(j)
}
}
2、while条件循环
package loop
import (
"fmt"
"testing"
)
func TestWhileLoop(t *testing.T) {
//while(n < 5)的写法
for n := 0; n < 5; n++ {
fmt.Println(n)
}
}
3、无限循环
package loop
import (
"fmt"
"testing"
)
func TestInfiniteLoop(t *testing.T) {
//无限循环的写法
n := 0
for {
//.....
fmt.Println(n)
}
}
二、if 条件
1、标准写法
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
if condition-1 {
// code to be executed if condition-1 is true
} else if condition-2 {
// code to be executed if condition-2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
2、与其它主要编程语言的差异
a、condition 表达式结果必须为布尔值
b、支持变量赋值
if var declaration; condition {
// code to be executed if condition is true
}
package condition
import "testing"
func TestIfMultiSec(t *testing.T) {
//if 支持这这种先变量赋值,在写条件的写法,在结果函数可以有多返回值,可以很方便的做错误判断
if val,err = someFunc(); err == nil {
t.Log(true)
} else {
t.Log(false)
}
}
三、switch 条件
1、标准写法
package _switch
import (
"fmt"
"runtime"
"testing"
)
func TestSwitch(t *testing.T) {
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
//这里不需要写 break, go语言会自动break
case "linux":
fmt.Println("Linux.")
default:
fmt.Printf("%s.", os)
}
}
2、与其他主要编程语言的差异
- 条件表达式不限制为常量或者整数;
- 单个 case 中,可以出现多个结果选项,使用逗号分隔;
- Go语言不需要使用 break 来明确退出一个 case;
- 可以不设定 switch 之后的条件表达式,在此种情况下,整个 switch 结构与多个 if{...}elseif{...}的逻辑作用相同。
a、case后面跟多个选项示例
package _switch
import (
"fmt"
"runtime"
"testing"
)
//case 后面跟多个选项示例
func TestSwitchMultiCase(t *testing.T) {
for i := 0; i<5; i++ {
switch i {
//重点:Go语言中支持一个 case 后面跟多个选项
case 0, 2:
t.Log("It is even between 0-3")
case 1, 3:
t.Log("It is odd between 0-3")
default:
t.Log("It not between 0-3")
}
}
}
b、case 后面接表达式的示例
package _switch
import (
"fmt"
"runtime"
"testing"
)
//case 后面跟多个选项示例
func TestSwitchMultiCase(t *testing.T) {
for i := 0; i<5; i++ {
switch i {
//重点:Go语言中支持一个 case 后面跟多个选项
case 0, 2:
t.Log("It is even between 0-3")
case 1, 3:
t.Log("It is odd between 0-3")
default:
t.Log("It not between 0-3")
}
}
}
//case 后面接表达式的示例
func TestSwitchCaseCondition(t *testing.T) {
for i := 0; i<5; i++ {
switch {
case i%2 == 0:
t.Log("It is an even number")
case i %2 == 1:
t.Log("It is a odd number")
default:
t.Log("Unknown")
}
}
}
注:这篇博文是我学习中的总结,如有转载请注明出处:https://blog.csdn.net/DaiChuanrong/article/details/117755450
上一篇:Go运算符
下一篇:Go数组和切片