当前位置:网站首页>Golang's range
Golang's range
2022-07-03 08:13:00 【Bel_ AMI classmate】
Golang range example
range yes golang A traversal method commonly used in , go C++ It's very easy for beginners to see such a traversal method . But if you haven't thought about it carefully range How it works , Use in some specific scenarios range, It may not achieve the desired effect .
1.1 range Basic grammar
First of all, let's take a look at range Basic grammar of
At first golang I feel that this language is particularly rigorous in the detection of grammar . For example, variables defined but not used will report errors .
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
}
}
Obviously the first range The return value is the index value index, The second is the value value. Generally, the second method is common _ ,v = range x, use _ To discard unused values . When only one value is used to receive range There will be no error when returning , This is very unexpected , And the index value returned at this time .
1.2 range principle
Then let's take a look range Unexpected situation
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)
}
}
// The output is as follows , Because traversing map,index As the key ,value by map Corresponding value in , Each traversal is unordered
/* li => wang wang => wang zhou => wang */
But for the first time , You will find that this is different from the expected output . Whole map All real values in are wang. Why is that so ?
Then we try to output the following code
fmt.Println(m)
// At this time, the output content is as follows
//map[zhou:0xc000046400 li:0xc000046400 wang:0xc000046400]
We will find that map[string]*student Medium *student The final stored values are the same . The reasons are as follows :range It uses a copy of repeated assignment to traverse each target element , You can think of it as a variable of the target element type , Each iteration will copy the target element to range Prepared copy , And return .
Revised edition :
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)
}
perhaps
for i:=0;i<len(stus);i++ {
m[stus[i].Name] = &stus[i]
}
for k,v:=range m{
println(k,"=>",v.Name)
}
Here are two range Nested usage instances :
// setReqBodyLog Requested body The data falls into the log
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))
}
边栏推荐
- Compilation error: "not in executable format: file format not recognized"“
- E: 无法定位软件包 ros-melodic-desktop-full
- oracle中的 (+)是什么意思
- Install cross compiler arm none liunx gnueabihf
- Map的实现类的顺序性
- animation
- ArrayList
- Iterm2 setting
- [global product discovery 2] the first pure cloud augmented reality (AR) platform - Israel
- C语言-入门-精华版-带你走进编程(一)
猜你喜欢

vcs import src < ros2. Repos failed

Unity change default editor
![[step on the pit series] MySQL failed to modify the root password](/img/d0/f975baf18bac506208abff3713ac03.png)
[step on the pit series] MySQL failed to modify the root password

the installer has encountered an unexpected error installing this package

Lua framwrok framework starts

the installer has encountered an unexpected error installing this package

Wechat applet taro learning record

方正锐利重磅升级到12.0版本,包装印前处理更加便捷、高效!

Puhua PLM empowers the whole scene product lifecycle management and helps the enterprise digital transformation of the main line of products

About the problem that the editor and the white screen of the login interface cannot be found after the location of unityhub is changed
随机推荐
Oracle insert single quotation mark
Youyou1 of xlua knapsack system
C language learning notes (mind map)
Idea dereference display effect
How to establish rectangular coordinate system in space
Wechat native applet cloud development learning record 01
Open the influence list of "National Meteorological Short Videos (Kwai, Tiktok) in November" in an interactive way“
A tunnel to all ports of the server
vcs import src < ros2. Repos failed
RM delete file
Ilruntime learning - start from scratch
Shader foundation 01
Golang url的编码和解码
oracle中的 (+)是什么意思
Unity XR realizes interaction (grasping, moving, rotating, transmitting, shooting) -pico
LinkList
Compilation error: "not in executable format: file format not recognized"“
My touch screen production "brief history" 2
Generate video using clipout in viz engine
Usage of (case, when) in PostgreSQL