分支结构
if-else
if
和else if
的控制条件不用使用括号括住。但要记住,执行开始的左括号{
要和条件位于同一行。例子:
rand.Seed(time.Now().Unix())//设置随机种子
a:=rand.Intn(3)//在0,1,2中随机
if a==0{ //{要和条件语句在同一行
fmt.Println("a=0")
}else if a==1{
fmt.Println("a=1")
}else {
fmt.Println("a=2")
}
switch-case
和c++
语言不同。go
中的case
不用每一条都去加break
语句。当匹配了其中一个case
后,会自动退出。
rand.Seed(time.Now().Unix())
a:=rand.Intn(3)
switch a {
case 0:
fmt.Println("a=0")
case 1:
fmt.Println("a=1")
default:
fmt.Println("a=2")
}
同时,go
中的switch-case
还可用于接口类型的判断。根据类型去执行不同的case
,这在函数参数传递中比较有用。例子:
func type_switch(a interface{}){
switch a.(type) {
case int:
fmt.Println("int 型",a)
case float64:
fmt.Println("float64 型",a)
case bool, string:
fmt.Println("bool 或 string 型",a )
default:
fmt.Println("未知型",a)
}
}
func main() {
a:=true
b:=123
c:=1.2
type_switch(a)
type_switch(b)
type_switch(c)
}
/*
输出:
bool 或 string 型 true
int 型 123
float64 型 1.2
*/
循环结构
类似while的for循环
go
中没有while
作为关键字的循环。但以下循环和while
相似:
a:=1
for a<10{
fmt.Print(a," ")
a++
}
/*输出:
1 2 3 4 5 6 7 8 9
*/
类c的for循环
c
语言中,for
循环的形式一般为:for(int i=0;i<10;i++)
。go
中和这个写法相似的for
循环写法为:
for a:=1;a<10;a++{
fmt.Print(a," ")
}
迭代循环
作用与可迭代的参数上。对于切片和数组,接收的第一个参数为下标,第二个参数为下标对应的值*(可以不接收第二个参数)。对于map
,第一个参数为key
,第二个参数为key
对应的value
(可以不接受)*。例子:
var a []int=make([]int,5)
for i:=range a{//只接收一个参数。即为a的下标
a[i]=i*i
}
for _,k:=range a{//_代表接收但是不打算使用。k为a的元素
fmt.Print(k," ")
}
/*
输出:
0 1 4 9 16
*/
a[i]=ii
}
for _,k:=range a{//_代表接收但是不打算使用。k为a的元素
fmt.Print(k," ")
}
/
输出:
0 1 4 9 16
*/