获取在Golang中存储在reflect.Value中的变量的指针。

huangapple go评论82阅读模式
英文:

get pointer to variable stored in reflect.Value in Golang

问题

可能这个问题很简单,但是我花了一些时间,却找不到任何好的解决办法(
例如,我们有以下代码:

var someValue int = 10
v := reflect.ValueOf(someValue)
var v1 reflect.Value // 应该只使用 "v" 变量来引用 &someValue

我知道最简单的解决办法是 v1 := reflect.ValueOf(&someValue) 或者使用 reflect.New() 函数,但不幸的是,在我的情况下这样做不起作用。

"v1" 变量应该只使用 "v" 变量来初始化。

英文:

Probably this is question is very simple, but i've spent some time and was not able to find any good solution(
For example we have the following code:

var someValue int = 10
v := reflect.ValueOf(someValue)
var v1 reflect.Value // should refer to &someValue, but with using of the "v" variable only

I know that the easiest solution will be v1 := reflect.ValueOf(&someValue) or using of reflect.New() function, but unfortunately this will not work in my case.

The "v1" variable should be initialized only with using of the "v" variable.

答案1

得分: 2

当你调用reflect.ValueOf(someValue)时,ValueOf会接收到someValue的一个副本。在调用点上,ValueOf的参数地址与someValue的地址是不同的。

无论ValueOf返回什么,它都不可能知道原始someValue的地址,所以你在这里想要实现的是不可能的。

你能做的最好的办法是调用Value.Addr,它将返回一个表示传递给ValueOf的someValue副本地址的reflect.Value:

var someValue int = 10
v := reflect.ValueOf(someValue)
v1 := v.Addr() // 表示指向someValue副本的*int的reflect.Value
var p1 *int = v1.Interface().(*int) // 与&someValue不同的地址
英文:

When you call reflect.ValueOf(someValue), ValueOf is passed a copy of someValue. The address of the argument to ValueOf is different from the address of someValue at the call site.

Whatever ValueOf returns cannot possibly know about the address of the original someValue, so what you want to achieve here is impossible.

The best you can do is call Value.Addr, which will return a reflect.Value representing the address of the copy of someValue that was passed to ValueOf:

var someValue int = 10
v := reflect.ValueOf(someValue)
v1 := v.Addr() // reflect.Value representing a *int pointing to a copy of someValue
var p1 *int = v1.Interface().(*int) // distinct from &someValue

huangapple
  • 本文由 发表于 2023年1月23日 22:20:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75210794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定