Getting a pointer of a value with reflect?

Written by
reddit
Link to Post

https://www.reddit.com/r/golang/comments/bo0erb/getting_a_pointer_of_a_value_with_reflect/ by 

Hi,

I’m trying to figure out what’s the equivalent of:

&a 

using the reflect package, due to not knowing the input type, except that its pointer implements a known interface. In an essence, I want to create a function like this:

func ptr(v interface{}) v interface{} { // Not wokring: return &v (type will be (*interface{}) p := reflect.New(reflect.ValueOf(v).Type()) // FIXME: set value of p to v return p.Interface() } 

I can create a proper pointer of the type, but I do not know how to set its value to that of “v”. I could probably marshal the data in v and then unmarshal it into “p”, but that seems rather overkill.

submitted by /u/saturn_vk
[link] [comments]

Article Tags:
· ·
Article Categories:
reddit

Leave a Reply