Golang 开发实战day05 - Loops(1)

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

相关推荐

  1. Golang 开发实战day05 - Loops(1)

    2024-03-20 11:08:08       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-20 11:08:08       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-20 11:08:08       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-20 11:08:08       82 阅读
  4. Python语言-面向对象

    2024-03-20 11:08:08       91 阅读

热门阅读

  1. 2020.9.8C++Primer学习笔记————模板函数

    2024-03-20 11:08:08       41 阅读
  2. uniapp:wx.switchTab: url 不支持 queryString

    2024-03-20 11:08:08       38 阅读
  3. docker离线安装

    2024-03-20 11:08:08       41 阅读
  4. Android 12 SystemUI调试

    2024-03-20 11:08:08       37 阅读
  5. 模拟计算机和数字计算机

    2024-03-20 11:08:08       37 阅读
  6. 服务器时间不准确的风险

    2024-03-20 11:08:08       37 阅读
  7. Python基础----冒泡排序和二分查找(持续更新中)

    2024-03-20 11:08:08       40 阅读
  8. LeetCode题练习与总结:组合总和Ⅱ

    2024-03-20 11:08:08       43 阅读
  9. HTTP与TCP的特点

    2024-03-20 11:08:08       35 阅读
  10. C++ 面试100问--完结(十一)

    2024-03-20 11:08:08       39 阅读
  11. C++ 中的 Pimpl 惯用法

    2024-03-20 11:08:08       36 阅读
  12. etcd 和 Redis 的对比:特点与适用场景

    2024-03-20 11:08:08       39 阅读