Programming/golang

golang 변수 타입 알아내기

구차니 2022. 10. 5. 23:44

 refelct 패키지의 reflect.TypeOf()를 통해 :=로 할당된 객체의 타입을 알아낼 수 있다.

package main

import (
    "fmt"
    "reflect"
)

func main() {

    tst := "string"
    tst2 := 10
    tst3 := 1.2

    fmt.Println(reflect.TypeOf(tst))
    fmt.Println(reflect.TypeOf(tst2))
    fmt.Println(reflect.TypeOf(tst3))

}
Hello, playground
string
int
float64

[링크 : https://stackoverflow.com/questions/20170275/how-to-find-the-type-of-an-object-in-go]

 

func TypeOf(i any) Type
TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

[링크 : https://pkg.go.dev/reflect]

[링크 : https://pkg.go.dev/reflect#TypeOf]