【Go言語】特定のメソッドを持っているかどうかチェックする。

以下のようにチェックできます。

package main

import (
    "fmt"
)

type Animal interface {
    Eat()
}

type Human struct {
    Name string
}

func (h *Human) Eat() {
    fmt.Println("eating!!")
}

func (h *Human) Hello(){
    fmt.Printf("Hello, %v", h.Name)
}

//存在チェックしたいメソッドを持つインターフェースを定義
type Hello interface {
    Hello()
}

func check(animal Animal)bool {
    if _, ok := animal.(Hello); ok {
        return true
    }
    return false
}


func main() {
    h := &Human{Name: "bob"}
    if check(h) {
        fmt.Println("Human has Hello() method.")
    }
}

play.golang.org