Wednesday, 15 August 2012

go - why can't I use reflection to take the address of a slice? -



go - why can't I use reflection to take the address of a slice? -

how come works:

slice := make([]string, 0, 10) sliceptr := &slice

this too:

sliceptr := &[]string{"foo","bar","baz"}

but doesn't:

sliceaddrval := reflect.valueof([]string{"foo","bar","baz"}).addr()

it panics with: reflect.value.addr of unaddressable value

edit: overall i'm trying take struct of unknown type, create piece of structs of type , homecoming pointer (i'm using github.com/jmoiron/modl requires pointer piece populate results sql query).

reflect.value takes interface{}, , interface{} value can't used alter original. otherwise, end code changing info in struct when didn't intend pass pointer. (or, in case, changing length of piece passed value.) if take address you'd have before valueof.

to create pointer piece can pass bundle append (like modl or google app engine getmulti), you'd utilize http://play.golang.org/p/1zxsqjrqa3, copied here:

package main import ( "fmt" "reflect" ) type row struct { i, j int } func main() { arow := row{} valuetype := reflect.valueof(arow).type() sliceptrval := reflect.new(reflect.sliceof(valuetype)) sliceptriface := sliceptrval.interface() getqueryresults(sliceptriface) fmt.println(sliceptriface) } // standing in `modl` or whatever populates piece func getqueryresults(sliceptr interface{}) { sptr := sliceptr.(*[]row) (*sptr) = append((*sptr), row{1,3}) }

appending piece in reflect.value takes few lines of reflect, sounds bundle you're working takes care of part you. general info, code append @ http://play.golang.org/p/m3-xfyc6on , below:

package main import ( "fmt" "reflect" ) type row struct { i, j int } func main() { arow := row{} // create pointer empty piece rowtype := reflect.valueof(arow).type() sliceptrval := reflect.new(reflect.sliceof(rowtype)) sliceptriface := sliceptrval.interface() // append 0 row rowval := reflect.zero(rowtype) sliceval := reflect.indirect(sliceptrval) sliceval.set(reflect.append(sliceval, rowval)) fmt.println(sliceptriface) }

reflection go slice

No comments:

Post a Comment