How to get underlying value from a reflect.Value in golang?

前端 未结 4 1594
星月不相逢
星月不相逢 2021-02-02 08:02

So I found some code that help me get started with reflection in Go (golang), but I\'m having trouble getting a the underlying value so that I can basically create a map[s

4条回答
  •  我在风中等你
    2021-02-02 08:31

    This should be easier to do with Go 1.5 (August 2015) See review 8731 and commit 049b89d by Rob Pike (robpike):

    fmt: treat reflect.Value specially - as the value it holds

    This would allow you to print the actual value of a Reflect.Value() argument:

    When a reflect.Value is passed to Printf (etc.), fmt called the String method, which does not disclose its contents.
    To get the contents, one could call Value.Interface(), but that is illegal if the Value is not exported or otherwise forbidden.

    This CL improves the situation with a trivial change to the fmt package: when we see a reflect.Value as an argument, we treat it exactly as we treat a reflect.Value we make inside the package.
    This means that we always print the contents of the Value as if that was the argument to Printf.

    This is arguably a breaking change but I think it is a genuine improvement and no greater a break than many other tweaks we have made to formatted output from this package.

提交回复
热议问题