24
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Golang 型確認

Last updated at Posted at 2020-05-04

reflect.TypeOfを使う場合

package main

import (
    "fmt"
    "reflect"
    "strings"
    "time"
)

func main() {
    // 数値
    P(1)                            // int
    P(1.2)                          // float64

    // 文字列
    P("string")                     // string

    // 配列
    P([]int{0,1,2})                 // []int
    P([2]int{0,1})                  // [2]int
    P([]string{})                   // []string
    P(strings.Split("a b", " "))    // []string
    P([1]string{"1"})               // [1]string

    // マップ
    P(map[string]int{"a": 10})      // map[string]int
    P(map[int]int{1: 10})           // map[int]int
    P(map[string]string{"1": "10"}) // map[string]string

    // その他
    P(true)                         // bool
    P(nil)                          // <nil>
    P(func() {})                    // func()
    P(P)                            // func(interface {})
    P(time.Now())                   // time.Time

}

func P(t interface{}) {
    fmt.Println(reflect.TypeOf(t))
}

fmt.Printfを使う場合

package main

import "fmt"

func main() {
    fmt.Printf("%T\n", 1) // int
    fmt.Printf("%T\n", "string") // string
}

参考

Golangで型情報を調べる
http://y0m0r.hateblo.jp/entry/20140413/1397397593

Go言語で型を判別する関数
https://teratail.com/questions/4795

24
6
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
24
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?