Go语言循环示例
时间:2020-01-09 10:38:46 来源:igfitidea点击:
如何使用Go编程语言编写for循环?
如何使用golang for loop重复执行某些任务?
如何在golang上使用for语句设置无限循环?
for循环是golang语句,它允许重复执行代码。
for循环被归类为迭代语句,即它是go程序内进程的重复。
例如,您可以运行某些任务或打印消息五次,或使用for循环读取和处理文件列表。
Golang for循环与forC的循环语法相似但不相同。
go lang for循环语法
基本语法为:
for init; condition; post {
// run commands till condition is true
}
无限for循环语法:
for {
// I will run forever
}
go lang循环示例
以下golang程序使用for循环打印欢迎消息五次。
创建一个名为for.go的文件:
// for.go : A simple for loop program written in golang
package main
// get fmt package for Printf()
import "fmt"
// Our main()
func main() {
// set a for loop
for i := 1; i
保存并关闭文件。
如下运行:
$ go run for.go
输出示例:
Welcome 1 times Welcome 2 times Welcome 3 times Welcome 4 times Welcome 5 times
这是另一个使用for循环打印所有数字之和的示例:
// sum.go : golang for loop demo code
package main
import "fmt"
func main() {
sum := 0
for i := 1; i
保存并关闭文件。
如下运行:
$ go run sum.go
输出示例:
Sum = 210
如何将golang用于无限循环?
可以使用空表达式创建无限for循环,例如:
// forver-in-love.go : an infinite loop example
package main
import "fmt"
func main() {
for {
fmt.Println("I am in love with the Terminal (hit Ctrl+C to stop)")
}
}
在此示例中,从键盘读取一个整数(数字)并在屏幕上显示消息:
// for2.go : A modified version of for.go. This program use Scan() to read input from user
package main
import "fmt"
func main() {
y := 0
// Get number from user
fmt.Printf("Enter a number : ")
fmt.Scan(&y)
for i := 1; i
输出示例:
$ go run for2.go Enter a number : 3 Welcome 1 times. Welcome 2 times. Welcome 3 times.
如何使用break关键字终止for循环?
解决方法:您需要使用break关键字,语法如下:
for .... {
if condition { break }
}
在此示例中,当我5岁时退出for循环:
//
// forbreakdemo.go : Terminate a loop using break keyword
//
package main
// get fmt package for Printf()
import "fmt"
// Our main()
func main() {
// set a for loop
for i := 1; i<=10; i++ {
//break out of for loop when i greater than 5
if i > 5 { break }
fmt.Printf("Welcome %d times\n",i)
}
fmt.Printf("Out of for loop...\n")
}
我如何进入for循环的开头?
解决方法:您需要使用continue关键字,语法如下:
for ... {
statement_1
if condition { continue }
statement_2
}
在此示例中,仅当我不是5时才打印消息:
// forcontinuedemo.go : The continue keyword demo
package main
// get fmt package for Printf()
import "fmt"
// Our main()
func main() {
// set a for loop
for i := 1; i<=10; i++ {
// only print welcome message if i is not 5
if i != 5 { continue }
fmt.Printf("Welcome %d times\n",i)
}
fmt.Printf("Outof for loop...\n")
}

