LoginSignup
3
3

More than 5 years have passed since last update.

Go言語:変数が関数かどうかを返す関数

Posted at

変数が関数かどうかを判断する関数です。
この関数はメタプログラミングすることが目的です。
reflect モジュールを使います。

func IsFunction(value interface{}) bool {
    if reflect.ValueOf(value).Type().Kind() == reflect.Func {
        return true
    }

    return false
}

サンプルコード:

main.go
package main

import (
    "log"
    "reflect"
)

func DoSomething() {}
type Foo struct {}
func (this *Foo) DoSomething() {}

func IsFunction(value interface{}) bool {
    if reflect.ValueOf(value).Type().Kind() == reflect.Func {
        return true
    }

    return false
}

func main() {
    log.Println(IsFunction(true))
    log.Println(IsFunction(1))
    log.Println(IsFunction("string"))
    log.Println(IsFunction(DoSomething))

    foo := &Foo{}
    log.Println(IsFunction(foo.DoSomething))
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3