Search code examples
pointersgointerfaceslicetype-assertion

Pointer to an empty interface type assertion


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?


Solution

  • 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?