Last active
February 2, 2018 19:16
-
-
Save Quar/7c33b33749014a9d8c84e01b7c41eb98 to your computer and use it in GitHub Desktop.
Golang Reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a trivial extension on SO6996704 | |
// `fmt.Printf("%T", x)` returns same as `reflect.TypeOf(x).Name()` | |
// without considering other aspects like impairments on execution time. | |
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
func PrintType(x interface{}) { | |
fmt.Printf("%v: %%T=%T, TypeOf.Kind=%s\n", x, x, reflect.TypeOf(x).Kind()) | |
} | |
func PrintName(x interface{}) { | |
fmt.Printf("%v: %%T=%T, TypeOf.Name=%s\n", x, x, reflect.TypeOf(x).Name()) | |
} | |
type Person struct { | |
name string | |
age int | |
} | |
func main() { | |
x := 1 | |
y := "hahaha" | |
z := Person{"John", 33} | |
PrintType(x) // 1: %T=int, TypeOf.Kind=int | |
PrintName(x) // 1: %T=int, TypeOf.Name=int | |
PrintType(y) // hahaha: %T=string, TypeOf.Kind=string | |
PrintName(y) // hahaha: %T=string, TypeOf.Name=string | |
PrintType(z) // {John 33}: %T=main.Person, TypeOf.Kind=struct | |
PrintName(z) // {John 33}: %T=main.Person, TypeOf.Name=Person | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment