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
相关推荐
烂蜻蜓1 小时前
Flask入门教程(十二):表单处理——从基础到Flask-WTF完整实践
后端·python·flask
Chester_19997 小时前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
2601_962055978 小时前
跟据spring boot版本,查看对应的tomcat,并查看可支持的tomcat的版本范围
spring boot·后端·tomcat
EXI-小洲8 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
会周易的程序员8 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
机器视觉知识推荐、就业指导8 小时前
为什么老说“纯 Qt 没啥就业市场”?
开发语言·qt
telepan9 小时前
Qt 开发避坑与性能指南:如何优雅、安全地定义全局常量字符串?
开发语言·qt
m0_695251499 小时前
Qt MaintenanceTool 使用国内镜像加速下载(超详细教程)
开发语言·qt
Lost of 程序猿9 小时前
ASP.NET Core API 幂等性设计深度实战:从一次重复申领事故说起
后端·asp.net
大衛說10 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习