dimanche 14 février 2021

Check if interface{} is ptr to struct

I would like to check if a given f interface{} function argument is a pointer to a struct, but am struggling somehow:

Updated snippet:

package main

import (
    "fmt"
    "log"
    "reflect"
)

func main() {

    // Switch f between being a pointer or not
    f := &struct{Foo string}{"Bar"}

    if err := something(f); err != nil {
        log.Fatal(err.Error())
    }

}

func something(f interface{}) error {

    if reflect.ValueOf(f).Kind() != reflect.Struct  {
        return fmt.Errorf("not struct; is %s", reflect.ValueOf(f).Kind().String())
    }

    if reflect.ValueOf(f).Kind() != reflect.Ptr  {
        return fmt.Errorf("not ptr; is %s", reflect.ValueOf(f).Kind().String())
    }

    // Deal with element values...
    t := reflect.ValueOf(f).Elem()

    for i := 0; i < t.NumField(); i++ {
        fmt.Println(t.Type().String(), t.Field(i).Interface())
    }

    return nil
}

If f is passed to function as pointer i get a not struct; is ptr.

If f is passed to function as struct i get a not ptr; is struct.

Is there any way to make sure that the interface is a pointer to a struct? Seems like as soon as f is a pointer any further checks via reflection are not usable here. Many other solutions I found could get handled via type assertions but I just do not know what is coming in here. Basically it could be literally anything.

Sure I could just use the pointer check and leave everything else as a "developer error". I just thought I could handle it somehow.

Any ideas?





Aucun commentaire:

Enregistrer un commentaire