ufk
ufk

Reputation: 32104

how to create a pointer to reflect.Value

I see many questions that appear to ask what I'm asking but I didn't see any actual response to the general question, just specific stuff.

I have reflect.Value of an int with a value of 64.

I have a slice that I got with reflection, that the type of the items in the slice is *int.

newSlice := reflect.Append(slice, currentRow.Convert(slice.Type().Elem()))
slice.Set(newSlice)

if I just run this, I get panic: reflect.Value.Convert: value of type int cannot be converted to type *int

I tried to run currentRow.Interface() but it returns an interface type pointer that cannot be added to the slice.

so how can I do that properly ?

I cannot know if it will be *int, or *string or anything else, I need it to be genneric

Upvotes: 0

Views: 1683

Answers (2)

Thundercat
Thundercat

Reputation: 120951

Copy the value to a variable:

v := reflect.New(currentRow.Type())
v.Elem().Set(currentRow)

Add the address of the variable to the slice:

newSlice := reflect.Append(slice, v)
slice.Set(newSlice)

Upvotes: 3

Burak Serdar
Burak Serdar

Reputation: 51577

If you have a reflect.Value, and if that value is addressable, that is, if value.CanAddr() returns true, then value.Addr() returns a reflect.Value that has a pointer to the value.

Upvotes: 0

Related Questions