英文:
Which different variables does range clause return for different data structure types like map?
问题
当循环遍历一个数组时,第一个返回的变量是索引,第二个返回的变量是值:
array := []int{2, 3, 4}
for index, value := range array {
fmt.Printf("索引: %s, 值: %s\n", index, value)
}
当使用range子句循环遍历一个映射(map)时,返回的内容与数组不同。映射中没有索引的概念,但我们可以获取键名。
英文:
When looping through an array, the first variable returned is the index, and the second variable returned is the value:
array := []int{2, 3, 4}
for index, value := range array {
fmt.Printf("Index: %s, Value: %s\n", index, value)
}
What is returned when looping through map with the range clause. It is not the same as for array. There cannot be an index of a map anyway. Can we get key names?
答案1
得分: 3
根据range子句的文档,以下是它与不同类型一起使用时返回的值:
-
数组或切片
a [n]E、*[n]E或[]E:- 第一个值: 索引
i int - 第二个值(可选):
a[i]的元素 E
- 第一个值: 索引
-
字符串
s string类型:- 第一个值: 索引
i int - 第二个值(可选): 字符的 Unicode 值
int(要获取实际字符,只需进行类型转换,如string(value))
- 第一个值: 索引
-
映射
m map[K]V:- 第一个值: 键
k K - 第二个值(可选): 值
m[k]的类型 V
- 第一个值: 键
-
通道
c chan E:- 第一个值: 元素
e E
- 第一个值: 元素
英文:
As per the documentation of range clause, following are the returned values for different kinds of types that it is used with:
-
array or slice a
[n]E,*[n]E, or[]E: -
1st value: index
i int -
2nd value (optional):
a[i]E (element at index i) -
string s string type
-
1st value: index
i int -
2nd value (optional): rune
int(the unicode of the character. to get the actual character, simply cast like this:string(value)) -
map m
map[K]V: -
1st value: key
k K -
2nd value (optional): value
m[k]V -
channel c chan E:
-
1st value: element
e E
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论