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 分钟前
基于SpringBoot的高校学习讲座预约系统-项目分享
spring boot·后端·学习
坐吃山猪4 分钟前
Python-Agent调用多个Server-FastAPI版本
开发语言·python·fastapi
88号技师6 分钟前
【1区SCI】Fusion entropy融合熵,多尺度,复合多尺度、时移多尺度、层次 + 故障识别、诊断-matlab代码
开发语言·机器学习·matlab·时序分析·故障诊断·信息熵·特征提取
Asthenia04128 分钟前
Reactor 模型详解:从单线程到多线程及其在 Netty 和 Redis 中的应用
后端
北漂老男孩21 分钟前
Java对象转换的多种实现方式
java·开发语言
未来可期LJ33 分钟前
【Test】单例模式❗
开发语言·c++
Arenaschi43 分钟前
SQLite 是什么?
开发语言·网络·python·网络协议·tcp/ip
听雨·眠1 小时前
go语言中defer使用指南
开发语言·后端·golang
Yhame.1 小时前
【使用层次序列构建二叉树(数据结构C)】
c语言·开发语言·数据结构
言之。1 小时前
【Go语言】RPC 使用指南(初学者版)
开发语言·rpc·golang