mardi 6 octobre 2020

getting reflect.Value(&foo) from reflect.Value(foo)

the title of the question pretty much sums it up. I'm playing with reflections using Go, and I'm trying to get the address of what reflect.Value() is pointing at.

why?

I have a function that can receive a struct in two ways: first.. this is the struct

type UserInfo struct {
    Name   string        `json:"name"`
    Roles  *[]model.Role `json:"role"`
    UserId int           `json:"user_id" db:"id"`
}

one:

var userInfo types.UserInfo
myFunc(&userInfo)

with this method i'm good since since it's a pointer to a struct that has it's memory allocated

the 2nd method:

var userInfo *types.UserInfo
myFunc(userInfo)

so here if I do reflect.Value() it's a Nil Pointer. i want to allocate that struct and to point userInfo to the new place. now I can easily do that if I paste &userInfo as well and perform:

myFunc(dst interface{}, dstAddr interface{})
{
 v := reflect.ValueOf(dstAddr)
 t := reflect.TypeOf(dst)
 ptr := reflect.New(t.Type())
 ...
 v.Elem().Set(ptr)
}

now I would except that reflect.ValueOf(dst).Addr() will be the same as reflect.ValueOf(&dst) but actually reflect.ValueOf(dst).CanAddr() returns false.

so.. is there a way to get reflect.ValueOf(&dst) while only having reflect.ValueOf(dst) ?





Aucun commentaire:

Enregistrer un commentaire