vendredi 25 mars 2022

Golang: Get the pointer to a struct using reflection

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

    // 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?





Aucun commentaire:

Enregistrer un commentaire