This was also my swag at an example: https://play.golang.org/p/QG7g9veKEI
PS: it's still not strictly "type safe". On Mon, Nov 7, 2016 at 4:46 PM Edward Muller <edwar...@interlix.com> wrote: > Why do you want to use pointers? > > On Mon, Nov 7, 2016 at 4:42 PM Kaylen Wheeler <kfjwhee...@gmail.com> > wrote: > > Thanks for the "basic pattern" example here. There's one little > modification I'm wondering about. > > Can this line: > > rv.Elem().Set(m[rv.Type()]) > > be changed to this? > > rv.Elem().Set(*&*m[rv.Type()]) > > If so, how can we check that the input value is a pointer to a pointer. > > Or alternatively, is it better that the values in m should be pointers? > > > On Monday, 7 November 2016 16:01:53 UTC-8, adon...@google.com wrote: > > On Monday, 7 November 2016 17:55:57 UTC-5, Kaylen Wheeler wrote: > > I'm trying to find a typesafe way to access a type-indexed map of > components. This map can contain objects of any type, and the keys are > reflect.Type. > > One strategy I thought may work would be to pass a pointer to a pointer as > an out-var. Using reflection to determine the pointer's type, it could be > populated with a corresponding value. > > For instance, if we did something like this: > > c := ComponentCollection{} > c.addComponent(123) // Add an int component > > var p : *int > c.getComponent(&p) > > > In this case, p would point to the int component of c. > > That's wht the 2 levels of indirection are necessary: it's an out-var to a > pointer. > > Does that make sense? > > > Here's the basic pattern: > > var m = make(map[reflect.Type]reflect.Value) > > func addComponent(x interface{}) { > v := reflect.ValueOf(x) > m[v.Type(x)] = v > } > > func getComponent(ptr interface{}) { > rv := reflect.ValueOf(ptr) > if rv.Kind() != reflect.Pointer { > panic("not a pointer") > } > rv.Elem().Set(m[rv.Type()]) > } > > -- > 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+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > > -- 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+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.