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
相关推荐
喵了meme7 小时前
C语言实战4
c语言·开发语言
码界奇点7 小时前
Python从0到100一站式学习路线图与实战指南
开发语言·python·学习·青少年编程·贴图
码事漫谈7 小时前
C++ 多线程开发:从零开始的完整指南
后端
9ilk7 小时前
【C++】--- 特殊类设计
开发语言·c++·后端
码事漫谈7 小时前
十字路口的抉择:B端与C端C++开发者的职业路径全解析
后端
sali-tec8 小时前
C# 基于halcon的视觉工作流-章68 深度学习-对象检测
开发语言·算法·计算机视觉·重构·c#
提笔了无痕8 小时前
git基本了解、常用基本命令与使用
git·后端
java1234_小锋9 小时前
Spring IoC的实现机制是什么?
java·后端·spring
喵个咪9 小时前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:JWT 集成指南
后端·go
生骨大头菜9 小时前
使用python实现相似图片搜索功能,并接入springcloud
开发语言·python·spring cloud·微服务