Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of the range keyword in Go

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

这篇文章主要介绍"Go语言中的range关键字有什么用"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"Go语言中的range关键字有什么用"文章能帮助大家解决问题。

关键字range可用于循环,类似迭代器操作,它可以遍历slice,array,string,map和channel,然后返回索引或值。可以使用"_"来忽略不想要的返回值。可以方便的读取上面类型中的内容,例如:

package mainimport "fmt"func main() { str1 := []string{"1", "2", "3", "4"} for key, value := range str1 { fmt.Println(key, ":", value) }}

但是如果想要改变这些类型的值,用range就可能达不到你期望的效果。例如,将上面str1中的值"2"和"4"变为"6",使用range来进行遍历修改。

package mainimport "fmt"func main() { str1 := []string{"1", "2", "3", "4"} for _, value := range str1 { if value == "2" || value == "4" { value = "6" } } fmt.Println(str1)}

你可能觉得结果会是[1 6 3 6],但执行后却是[1 2 3 4]。也就是说在range中对切片进行操作,并没有影响到切片(原切片)。

出现上述问题的原因是因为for range遍历的内容是对原内容的一个拷贝,所以不能用来修改原切片中内容。

修改方法:

使用for语句

package mainimport "fmt"func main() { str1 := []string{"1", "2", "3", "4"} for i := 0; i < len(str1); i++ { if str1[i] == "2" || str1[i] == "4" { str1[i] = "6" } } fmt.Println(str1)}关于"Go语言中的range关键字有什么用"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注行业资讯频道,小编每天都会为大家更新不同的知识点。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report