当前位置:网站首页>Golang的range
Golang的range
2022-07-03 08:04:00 【Bel_Ami同学】
Golang range实例
range 是 golang中特别常用的一种遍历方式,走C++入门的看到这样的遍历方式感觉太好用了。但是如果没有认真思考过range的工作原理,在一些特定的场景使用range,可能并不能达到预期的效果。
1.1 range基础语法
首先我们先来看一下range的基础语法
一开始认识golang 感觉这门语言对语法的检测特别严谨。比如定义但是没有使用的变量就会报错。
package main
import "fmt"
func main() {
x := []string{
"a", "b", "c"}
for v := range x {
fmt.Println(v) //prints 0, 1, 2
}
for _, v := range x {
fmt.Println(v) //prints a, b, c
}
}
很明显第一个range返回值为索引值index,第二个为值value。一般常见的都是第二种方式 _ ,v = range x,用_来丢弃不用的值。当只用一个值来接收range返回的时候也不会报错,这个就很意外了,并且这个时候返回的为索引值。
1.2 range原理
然后我们来看一下range的意外状况
package main
import "fmt"
type student struct {
Name string
Age int
}
func main() {
m := make(map[string]*student)
stus := []student{
{
Name: "zhou", Age: 24},
{
Name: "li", Age: 23},
{
Name: "wang", Age: 22},
}
for _, stu := range stus {
m[stu.Name] = &stu
}
for k, v := range m {
fmt.Println(k, "=>", v.Name)
}
}
//输出情况如下,因为遍历map,index为键,value为map中对应的值,每次遍历是无序的
/* li => wang wang => wang zhou => wang */
但是初次遇到这种情况,大家就会发现这和预期的输出不一样。整个map中的所有实值都是wang。为什么会是这样?
然后我们尝试以下边的代码做输出
fmt.Println(m)
//此时输出内容如下
//map[zhou:0xc000046400 li:0xc000046400 wang:0xc000046400]
我们会发现map[string]*student 中的 *student最终存储的值都是一样的。究其原因如下:range 是使用一个副本重复赋值的方式来遍历每一个目标元素的,可以将其视为一个目标元素类型的变量,每一次遍历迭代就会把目标元素拷贝到range准备的副本,并作返回。
修改版:
for k, stu := range stus {
fmt.Println(stu.Name, "=>", &stu)
m[stus[k].Name] = &stus[k]
}
for k,v:=range m{
println(k,"=>",v.Name)
}
或者
for i:=0;i<len(stus);i++ {
m[stus[i].Name] = &stus[i]
}
for k,v:=range m{
println(k,"=>",v.Name)
}
下面是两个range嵌套使用实例:
// setReqBodyLog 请求的body数据落日志
func setReqBodyLog(ctx context.Context, req *http.Request) {
formMap := map[string]string{
}
for k, v := range req.PostForm {
for _, formV := range v {
if formMap[k] == "" {
formMap[k] = desensitization.RemoveSensetive(formV)
} else {
formMap[k] += "," + desensitization.RemoveSensetive(formV)
}
}
}
logit.ReplaceMetaFields(ctx, logit.AutoField(transmitEntities.LogReqBody, formMap))
}
边栏推荐
- Puhua PLM empowers the whole scene product lifecycle management and helps the enterprise digital transformation of the main line of products
- Project experience sharing: handwritten Chinese character recognition based on Shengsi mindspire
- E: Unable to locate package ROS melody desktop full
- 数据库应用技术课程设计之商城管理系统
- About Wireshark's unsuccessful installation of npcap
- Yolo series --- xml2txt script
- Unity performance optimization
- Demonstration of plug-in use of ventuz basic series
- Clip Related Script
- Quality blog——
猜你喜欢

the installer has encountered an unexpected error installing this package

一个实习生的CnosDB之旅

I want to do large screen data visualization application feature analysis

一条通往服务器所有端口的隧道

Unity2019_ Natural ambient light_ Sky box

*p++、*++p、++*p、(*p)++

Pycharm remote ssh pyenv error: pydev debugger: warning: trying to add breakpoint to file that does

Scite change background color

haproxy+keepalived搭建01

the installer has encountered an unexpected error installing this package
随机推荐
P2704 [NOI2001] 炮兵阵地(状压dp)
YOLO系列 --- xml2txt脚本
[set theory] order relation (hastu example | divisive relation hastu | inclusive relation hastu | refinement relation hastu)
An intern's journey to cnosdb
Unity2019_ Natural ambient light_ Sky box
Oracle insert single quotation mark
Lua hot update basic grammar
Quality blog——
链式长取值
Pycharm remote ssh pyenv error: pydev debugger: warning: trying to add breakpoint to file that does
Huawei s5700 switch initialization and configuration SSH and telnet remote login methods
freetype库的移植
Oracle queries grouped by time
Viz artist advanced script video tutorial -- stringmap use and vertex operation
Install cross compiler arm none liunx gnueabihf
How can entrepreneurial teams implement agile testing to improve quality and efficiency? Voice network developer entrepreneurship lecture Vol.03
P2704 [noi2001] artillery position (shape pressure DP)
Youyou1 of xlua knapsack system
The difference between hdmi2.1 and hdmi2.0 and the conversion of PD signals.
Haproxy+kept cluster setup 02