In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Golang中的控制流是怎样的,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
控制结构分为: 条件+选择+循环
IF
1.说明
代码如下:
条件表达式没有括号
支持一个初始化表达式(可以是多变量初始化语句)
初始化语句中定义的都是只能在block级别中使用的局部变量,不能在block之外使用
左大括号必须和条件语句在同一行(必须与if/else在同一行)
go没有三元运算符
if判断语句条件不需要括号
在判断语句里卖弄允许声明一个变量,其作用域只在逻辑块内,其他地方不起作用
花括号一定存在,且必须与if/else在同一行
2.语法
代码如下:
//基本
if a > 0 { //无括号
dosomething()
} else if a == 0 { //必须用花括号
doothertings()
} else {
donothing()
}
//单行模式
if a > 0 { a += 100 } else { a -= 100 }
3.示例
代码如下:
package main
func main(){
a := 10
if a > 0 {
a += 100
} else if a == 0 {
a = 0
} else {
a -= 100
}
println(a)
b := 101
if b > 0 { b += 100 } else { b -= 100 }
println(b)
}
//支持一个初始化语句
if a:=1; a 10 {
} else {
}
4.结果
代码如下:
110
201
注意,在有返回值的函数中,不允许将"最终的"return语句放到if ... else ... 结构中,否则编译失败
代码如下:
func example(x int) int {
if x == 0 {
return 5
} else {
return x
}
}
FOR
for是go的"while", 只支持for关键字.有三种形式
1.语法
代码如下:
for init; condition; post {
//init不支持逗号,只能平行赋值
//condition每次循环开始都会检查,不建议在里面使用函数,建议用计算好的变量/常量代替
//post后面必须跟花括号,每轮循环结束的时候调用
}
for i:=0; i 1:
println("a")
case a > 2:
println("b")
default:
println("c")
}
goto break continue
均可配合标签使用(标签区分大小写,若声明了没有使用会导致编译错误)
break/continue可配合标签用于多重循环跳出
goto是调整执行位置,与其他两个执行结果并不相同
1.goto
支持函数内部goto跳转
请善用
必须跳转到当前函数内定义的标签,标签名大小写敏感
代码如下:
func myFunc() {
i := 0
Here:
println(i)
i++
goto Here
}
2.continue
进入下一次循环
3.break
终止循环
代码如下:
for index := 10; index > 0; index -- {
if index == 5 {
break //continue
}
}
示例
代码如下:
package main
func main(){
a := 1
LABEL1:
println("inc a=", a)
a += 1
LABEL2:
//println("here")
for ; a < 6; {
println(a)
if a == 3 {
a += 1
continue LABEL2
}
if a == 5 {
break
}
goto LABEL1
}
}
结果:
代码如下:
inc a= 1
2
inc a= 2
3
4
inc a= 4
5
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.