Golang:使用反射获取指向结构的指针
我正在尝试编写递归遍历结构并跟踪指向其所有字段的指针以进行基本分析(大小、引用数量等)的代码。但是,我遇到了一个问题,我似乎无法通过反射来为我提供指向纯结构的指针。我有以下代码作为示例:
type foo struct {
A *bar
data []int8
}
type bar struct {
B *foo
ptrData *[]float64
}
func main() {
dataLen := 32
refData := make([]float64, dataLen)
fooObj := foo{data: make([]int8, dataLen)}
barObj := bar{
B: &fooObj,
ptrData: &refData,
}
fooObj.A = &barObj
fooVal := reflect.ValueOf(fooObj)
_ := fooVal.Addr().Pointer() // fails
_ := fooVal.Pointer() // fails
// More analysis code after this
}
如果我想遍历 fooObj
,那就没问题,直到我输入 barObj
,此时我再次遇到 fooObj.因为我没有办法获取初始
fooObj
遇到的指针,所以我最终遍历了 fooObj
两次,直到点击 barObj
第二次并退出递归。知道如何使用反射获取结构体的指针吗?
I'm trying to write code that recursively traverses a struct and keeps track of pointers to all its fields to do basic analysis (size, number of references, etc). However, I'm running into an issue where I can't seem to get reflection to give me the pointer to a pure struct. I have the following code as an example:
type foo struct {
A *bar
data []int8
}
type bar struct {
B *foo
ptrData *[]float64
}
func main() {
dataLen := 32
refData := make([]float64, dataLen)
fooObj := foo{data: make([]int8, dataLen)}
barObj := bar{
B: &fooObj,
ptrData: &refData,
}
fooObj.A = &barObj
fooVal := reflect.ValueOf(fooObj)
_ := fooVal.Addr().Pointer() // fails
_ := fooVal.Pointer() // fails
// More analysis code after this
}
If I wanted to traverse fooObj
, that would be fine until I entered barObj
at which point I again encounter fooObj
. Because I don't have a way to get the pointer for the initial fooObj
encounter, I end up traversing fooObj
twice until I hit barObj
the second time and exit the recursion. Any idea how to get a struct's pointer using reflection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果可能的话,这需要一个值的指针。
This takes a pointer of a value if it's possible.
正如您所提到的,您的代码在这部分失败
In foo struct
data
不是指针值。您尝试在非指针类型上调用
reflect.Value.Addr().Pointer()
和reflect.Value.Pointer()
,从而导致错误。您可以通过检查类型是否实际上是
ptr
来防止这种情况As you mentioned, your code fails in this part
In
foo
structdata
is not a pointer value.You are trying to call
reflect.Value.Addr().Pointer()
andreflect.Value.Pointer()
on a non-pointer type, causing the error.You can prevent this condition by checking if the type is actually
ptr