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
相关推荐
小哈里18 分钟前
【pypi镜像源】使用devpi实现python镜像源代理(缓存加速,私有仓库,版本控制)
开发语言·python·缓存·镜像源·pypi
努力学习的小廉22 分钟前
【C++】 —— 笔试刷题day_29
开发语言·c++·算法
全栈派森27 分钟前
云存储最佳实践
后端·python·程序人生·flask
电商数据girl31 分钟前
酒店旅游类数据采集API接口之携程数据获取地方美食品列表 获取地方美餐馆列表 景点评论
java·大数据·开发语言·python·json·旅游
天天打码31 分钟前
python版本管理工具-pyenv轻松切换多个Python版本
开发语言·python
CircleMouse31 分钟前
基于 RedisTemplate 的分页缓存设计
java·开发语言·后端·spring·缓存
ktkiko1138 分钟前
顶层架构 - 消息集群推送方案
java·开发语言·架构
楠奕38 分钟前
python中使用neo4j
开发语言·python·neo4j
南斯拉夫的铁托1 小时前
labelimg安装及使用指南(yolo)
开发语言·python·yolo
六bring个六1 小时前
文件系统交互实现
开发语言·c++·qt·交互