0

I am receiving a pointer to an interface to my function, and I am trying to iterate over it. The underlying type is a string slice, which I can convert to it if I am using type interface{} and not a pointer to it *interface{} What is the best way to type assert pointer to interface? Using pointer because the value to be transformed is of huge size.

Code that doesn't work:

func convertMember(member *interface{})  {
    for _, members := range member.([]string) {

invalid type assertion: member.([]string) (non-interface type *interface {} on left)

Code that doesn't work with dereferencing pointer:

func convertMember(member *interface{})  {
    for _, members := range *member.([]string) {

invalid type assertion: member.([]string) (non-interface type *interface {} on left)

Code that works if I change the parent function to send an interface instead of its pointer:

func convertMember(member interface{})  {
    for _, members := range member.([]string) {

Or should I type assert it to string slice and use a pointer to it?

nohup
  • 3,105
  • 3
  • 27
  • 52
  • You dereference pointers with `*`; `(*member).([]string)`. But, *why* are you using a pointer to an interface? There's no reason here (or ever really) to use a pointer to an interface. – JimB Apr 11 '16 at 14:11
  • Thank you @JimB. I tried range `*member.([]string)` which apparently didnt work because I didn't give the curly brackets. I will point it out in the question. – nohup Apr 11 '16 at 14:29

1 Answers1

3

You need to dereferencing before assertion:

func convertMember(member *interface{})  {
    for _, members := range (*member).([]string) { ... }
}

But why do you want a pointer to interface? When a struct implements some interface, the pointer of that struct implements that interface too. So a pointer to interface is kind of never-need.

For your reference, here's a related question: Why can't I assign a *Struct to an *Interface?

Community
  • 1
  • 1
nevets
  • 4,631
  • 24
  • 40
  • Thank you. I tried de-referencing it as `range *member.([]string)`, but since I missed the brackets part, it didn;t work. I will add that part to the question. It worked. – nohup Apr 11 '16 at 14:30