samedi 26 août 2023

How to pass a method name (safely) in Go

Is it possible to pass a method name in a safe manner? Currently I'm simply passing the method name as a string and match it using reflect but I wonder if it would be possible to pass it in a more safe manner(i.e as below) to prevent misspelling it or code getting out of sync (i.e. method name being renamed).

 package main

func Exists[T any](method any) string {
    // we extract the method name from the method/function itself. Impossible?

    // return the method name if it exists
    return ""
}

func main() {
    //we pass the method itself instead of its name (i.e. "Hello")
    m := Exists[X](X.Hello)
    if m != "Hello" {
        panic("expected  Hello")
    }
}

type X struct{}

func (X) Hello()   {}
func (X) GoodBye() {}

Play me





Aucun commentaire:

Enregistrer un commentaire