当前位置:网站首页>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))
}
边栏推荐
- Worldview satellite remote sensing image data / meter resolution remote sensing image
- Lua hot update basic grammar
- Base64和Base64URL
- 链式长取值
- Golang 时间格式整理
- Clip Related Script
- 璞华PLM为全场景产品生命周期管理赋能,助力产品主线的企业数字化转型
- Are you still watching the weather forecast on TV?
- [global product discovery 2] the first pure cloud augmented reality (AR) platform - Israel
- WorldView卫星遥感影像数据/米级分辨率遥感影像
猜你喜欢

Un système de gestion de centre commercial pour la conception de cours de technologie d'application de base de données

數據庫應用技術課程設計之商城管理系統

C语言-入门-精华版-带你走进编程(一)
![[untitled]](/img/3d/27a7229e3f0ccf0ca5ae1f00a92513.jpg)
[untitled]
![[global product discovery 2] the first pure cloud augmented reality (AR) platform - Israel](/img/51/04f5a9dbd03438fbdf25545a81b7ba.jpg)
[global product discovery 2] the first pure cloud augmented reality (AR) platform - Israel

Install cross compiler arm none liunx gnueabihf

vcs import src < ros2. Repos failed

数据的存储

My touch screen production "brief history" 1

Lua framwrok framework starts
随机推荐
Unity2019_ Lighting system
Abstract classes and interfaces
Maxcompute string splitting function -split_ PART
L'installateur a été installé avec une erreur inattendue
unity2019_ Input management
Scite change background color
Three characteristics
Xlua task list youyou
Compilation error: "not in executable format: file format not recognized"“
jsutlis
Getting started with minicom
Ventuz Foundation Series "one step at the door"
Map的实现类的顺序性
Flex flexible box layout
Dotween plug-in
[end of 2021] National Meteorological Short Video (Kwai, Tiktok) influence list in December
2020-12-12
Unity one click AssetBundle
PIP uses image website to solve the problem of slow network speed
About Wireshark's unsuccessful installation of npcap