Golang range实例
rangegolangC++rangerange
1.1 range基础语法
rangegolang
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
}
}
rangeindexvalue_ ,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
然后我们尝试以下边的代码做输出
fmt.Println(m)
//此时输出内容如下
//map[zhou:0xc000046400 li:0xc000046400 wang:0xc000046400]
map[string]*student*studentrangerange
修改版:
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))
}