vendredi 2 octobre 2020

working with slices of pointers to structs with reflection

I'm trying to practice reflections with Go, I read a few articles but it seems like I'm missing some basic understanding that maybe you guys can clear out.

I wrote a simple app to demonstrate what I'm trying to achieve.

in general I want a function to receive a slice of a pointer to a struct as an interface type, and to fill it with data using reflections.

again. this example seems a bit useless but i minimized what i'm trying to achieve. I know how to find the column names of a struct, but i have no problem there so I removed it from the example.

so this is the code:

package main

import (
    "log"
    "reflect"
    "unsafe"
)

type MyTesting struct {
    MyBool   bool
    MyFloat  float64
    MyString string
}


func addRow(dst interface{}) {
    iValue := reflect.ValueOf(dst)
    iType := reflect.TypeOf(dst)
    // getting the Struct Type (MyTesting)
    structType := iType.Elem().Elem().Elem()
    // creating an instance of MyTesting
    newStruct := reflect.New(structType)
    // getting the current empty slice
    slice := iValue.Elem()
    // appending the new struct into it
    newSlice := reflect.Append(slice,newStruct)
    // trying to set the address of the varible to the new struct ? the original var is not a pointer so something here
    // is clearly wrong. I get the PANIC here, but if i remove that line, then rows stays nil
    reflect.ValueOf(&dst).SetPointer(unsafe.Pointer(newSlice.Pointer()))
    currentPlaceForRow := newStruct.Elem()
    structField := currentPlaceForRow.FieldByName("MyString")
    structField.SetString("testing")
}

func main() {
    var rows []*MyTesting
    addRow(&rows)
    log.Print(rows)
}

so in general i the function gets an un-initialized slice of pointers to MyTesting struct. i want in the function to create the first slice element and to set the value of MyString in the 1st element to "testing".

when I try to execute it I get:

panic: reflect: reflect.Value.SetPointer using unaddressable value

so working with reflections is a bit confusing for me.. can anyone please a shed a light on what I'm missing here ? :)





Aucun commentaire:

Enregistrer un commentaire