Re: [go-nuts] Passing a Pointer to an Arbitrary Struct Type

845 views
Skip to first unread message

Dan Kortschak

unread,
Apr 4, 2013, 1:23:44 AM4/4/13
to Robert Bieber, golan...@googlegroups.com
Have a look through the reflect package (you could also take some hints
from xml, json and gob, but reflect should be enough to get you
started).

Andrew Gerrand

unread,
Apr 4, 2013, 1:25:02 AM4/4/13
to Robert Bieber, golang-nuts
You want to pass in the pointer value as an interface{} value, and use reflect to dereference the pointer.

See the reflect package's Elem.Value method: http://golang.org/pkg/reflect/#Value.Elem

Andrew


On 4 April 2013 16:04, Robert Bieber <tehb...@gmail.com> wrote:
I'm trying to write a function that can accept a pointer to a struct of unknown type (via interface{}) and a *database/sql.Rows, and copy the values from the current cursor in the sql.Rows into fields of the struct with corresponding names, using reflection.  It might be that what I'm trying to do isn't really feasible in Go, but I think it's more likely that I'm just too much of a n00b to know how.

First I tried making the destination input to the function type *interface{}, but apparently that's not allowed.  Then I tried just passing a pointer in to a parameter of type interface{} and then dereferencing it into another interface{} variable to examine with reflect, but apparently you can't dereference a variable of type interface{} unless you use a type assertion to cast it to a definite pointer type (which of course I can't do because I don't know what type of struct it will be pointing to until runtime).  Is there a way to do what I'm trying to do with structs?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

roger peppe

unread,
Apr 4, 2013, 3:29:49 AM4/4/13
to Robert Bieber, golang-nuts
You might want to take a look at code.google.com/p/rog-go/exp/stquery,
which does
something similar.
Reply all
Reply to author
Forward
0 new messages