Golang 开发实战day05 - Loops(1)

🏆个人专栏
🤺 leetcode
🧗 Leetcode Prime
🏇 Golang20天教程
🚴‍♂️ Java问题收集园地
🌴 成长感悟
欢迎大家观看,不执着于追求顶峰,只享受探索过程

Golang 教程05 - Loops

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

1. for循环

1.1 定义

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

1.2 语法

for condition {
    // 循环体
}

1.3 例子

	x := 0
	for x < 5 {
		fmt.Println("value of x is:", x)
		x++
	}
	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
	names := []string{"大雄", "小叮当", "静香", "小夫"}

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

output:

大雄
小叮当
静香
小夫
	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 语法

for key, value := range collection {
    // 循环体
}

2.3 例子

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

output:

1
2
3
4
5
	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 小夫; 
	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
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值