vendredi 23 juillet 2021

How can I dynamically check if type implements an interface

Assuming I have an interface called Hello like:

type Hello interface {
   Hi() string
}

I want to write a function that get Hello and any interface and does something if Hello also implement another interface, like:


type Person interface {
  Name() int
}

type Animal interface {
  Leg() int
}

type hello struct{}

func (h hello) Hi() string {
    return "hello!"
}

func (h hello) Leg() int {
    return 4
}

func worker() {

   h := hello{}
  // Don't match
  check(h,(Person)(nil))
  // Match
  check(h,(Animal)(nil))

}

func check(h Hello, n interface{}) {
 // of course this doesn't work, should I use reflection, if so how?
  if _,ok := h.(n); ok {
  // do something 
  }
}

How should I implement check function?





Aucun commentaire:

Enregistrer un commentaire