Golang 开发实战day05 - Loops(1)

Golang 教程05 - Loops

Golang提供了多种循环语句,用于重复执行代码块。

1. for循环

1.1 定义

for循环是Golang中最常用的循环语句。它使用for关键字开头,后面跟一个条件表达式。条件表达式控制循环的执行次数。

1.2 语法

go 复制代码
for condition {
    // 循环体
}

1.3 例子

go 复制代码
	x := 0
	for x < 5 {
		fmt.Println("value of x is:", x)
		x++
	}
go 复制代码
	for i := 0; i < 5; i++ {
		fmt.Println("value of i is:", i)
	}

output:

复制代码
value of x is: 0
value of x is: 1
value of x is: 2
value of x is: 3
value of x is: 4
go 复制代码
	names := []string{"大雄", "小叮当", "静香", "小夫"}

	for i := 0; i < len(names); i++ {
		fmt.Println(names[i])
	}

output:

复制代码
大雄
小叮当
静香
小夫
go 复制代码
	mapTest := map[int]string{ 
		10:"大雄", 
		0:"小叮当", 
		11:"静香", 
	} 
	for key, value:= range mapTest { 
		fmt.Println(key, value)  
	} 

output:

复制代码
10 大雄
0 小叮当
11 静香

2. For-Range循环

2.1 定义

for-range循环用于遍历集合,如数组、切片、映射等。

2.2 语法

go 复制代码
for key, value := range collection {
    // 循环体
}

2.3 例子

go 复制代码
	arr := []int{1, 2, 3, 4, 5}
	for _, value := range arr {
	    fmt.Println(value)
	}

output:

复制代码
1
2
3
4
5
go 复制代码
	names := []string{"大雄", "小叮当", "静香", "小夫"}

	for index, value := range names {
		fmt.Printf("the value at index %v is %v; ", index, value)
	}

output:

复制代码
the value at index 0 is 大雄; the value at index 1 is 小叮当; the value at index 2 is 静香; the value at index 3 is 小夫; 
go 复制代码
	testChannel := make(chan int) 
	go func(){ 
			testChannel <- 100 
			testChannel <- 1000 
			testChannel <- 10000 
			testChannel <- 100000 
			close(testChannel) 
	}() 
	for i:= range testChannel { 
		 fmt.Println(i)  
	} 

output:

复制代码
100
1000
10000
100000
相关推荐
喵个咪2 分钟前
RushWind Admin — update_mask 写面:字段级白名单、显式清除与点路径合并
后端·rust
喵个咪12 分钟前
RushWind Admin — 多租户行级隔离与租户回收站:Viewer 三态、repo_shell! 与全域级联清除
后端·rust
喵个咪13 分钟前
RushWind CMS — 三服务拓扑:core 领域层、双 BFF 薄代理与一份契约的双面输出
后端·rust
eggwyw1 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
天多高_风不晓得1 小时前
Comparable 与 Comparator
后端
程序员鱼皮1 小时前
这 3 年 AI Agent 到底进化了啥?万字大白话,一次讲透!
前端·后端·aigc
一条Go1 小时前
SSH 命令审核流:为什么「能执行」必须先「被批准」
后端·架构·github
布莱克6051 小时前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
__underline__1 小时前
冷门Python知识点007篇:list[int]不是类,为什么能当基类?
后端·python
用户615218329961 小时前
为什么 String 是不可变的?看懂字符串常量池和底层实现
后端