go print "%+v" 可以打印私有变量;reflect遍

2019-07-18  本文已影响0人  wncbbnk

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,
    }
}
上一篇 下一篇

猜你喜欢

热点阅读