go print函数“%+v”可以访问私有变量(如果私有变量里有map,打印相当于读,会有map并发读写问题)
比如http ctx里,就会有所有连接的map,打印ctx会有并发读写问题。因此,需要使用context标准方法Value
package main
import (
"context"
"fmt"
)
func main() {
ctx := context.TODO()
ctx = context.WithValue(ctx, "name", "todd")
name := ctx.Value("name")
fmt.Printf("name: %+v\n", name)
age := ctx.Value("age")
fmt.Printf("age: %+v\n", age)
fmt.Println("vim-go")
}
reflect遍历struct却不可以
tree
.
├── main.go
└── user
└── user.go
1 directory, 2 files
main.go
package main
import (
"fmt"
"reflect"
"github.com/wncbb/refect_study/user"
)
func main() {
u := user.New()
// 会打印出私有变量age
fmt.Printf("u:%+v\n", u)
v := reflect.ValueOf(u)
elem := v.Elem()
t := elem.Type()
for i := 0; i < elem.NumField(); i = i + 1 {
// 当遍历到age时,会panic,因为age是私有变量
fmt.Printf("i:%d, name:%s, type:%v, value:%v\n",
i,
t.Field(i).Name,
elem.Field(i).Type(),
elem.Field(i).Interface())
}
fmt.Println("vim-go")
}
user.go
package user
type User struct {
Name string
age int
}
func New() *User {
return &User{
Name: "todd",
age: 12,
}
}
网友评论