vendredi 10 novembre 2023

Golang Reflect Methods for Any type

I have been banging my head against this for a couple days now.

My goal is to have a function like so:

func ListFuncs(x any) []string {
    inst := reflect.New(reflect.TypeOf(x))
    y := inst.Elem().Interface()

    t := reflect.TypeOf(y)
    var s []string
    for i := 0; i < t.NumMethod(); i++ {
        s = append(s, t.Method(i).Name)
    }

    return s
}

I know the above code doesn't make FULL sense, but I have been changing it non-stop, it should give a basic idea of what I WANT to do, but I cannot for the life of me list functions for "any". I cant even make it work when I case it to the class I KNOW it is.

I can only make it work when I do reflect.TypeOf(StructName{}) is this even possible to do without explicitly knowing the struct used or having a switch statement for all the possible structs?





Aucun commentaire:

Enregistrer un commentaire