0
0

More than 3 years have passed since last update.

Goでinterface引数の型がポインタのときに、ポインタの先が示す型を判別する

Last updated at Posted at 2020-09-22

reflect.ValueOf, reflect.Value.Elem を組み合わせるとできる。
(この方法はユーザー定義の型ではなく、言語がデフォルトで用意する型を判別するもの)

package main

import (
    "fmt"
    "reflect"
)

func check(i interface{}) {
    // interfaceのValueインスタンスを取得
    v1 := reflect.ValueOf(i)

    // ポインタの場合、さらにその先にある型を取得する処理に進む
    if v1.Kind() == reflect.Ptr {
        // Elemを利用して、ポインタの先のValueインスタンスを取得
        v2 := reflect.ValueOf(v1.Elem())
        // Kindを呼ぶと、ポインタの先にある型情報が得られる
        fmt.Println(v2.Kind())
    }
}

type Foo struct {}

func main() {
    s := Foo{}
    check(&s) // struct
}
0
0
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
0
0