1. 标准的三段式循环
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 100; i++ {
sum += i
}
fmt.Println(sum)
}
2. 使用range 遍历 sclice
package main
import "fmt"
func main() {
values := []int{1,3,5,7,9}
for _,value := range values{
fmt.Println(value)
}
}
3. 使用range 遍历map
package main
import "fmt"
func main() {
values := map[string]int{"Jane":10,"Lucy":3,"Jim":4}
for key,value := range values{
fmt.Println(key,value)
}
}
4. 使用range 遍历 channel
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
for i := 0; i < 3; i++ {
ch <-i
}
close(ch)
}()
// The loop will end when channel close
for value := range ch{
fmt.Println(value)
}
}
5. 无限循环由于 golang中没用while关键字因此无限循环需要使用for
package main
import (
"fmt"
"time"
)
func main() {
for {
fmt.Println("Hello USA")
time.Sleep(time.Second)
}
}