Create a gist now

Instantly share code, notes, and snippets.

A sample code, to use reflect and convert interface{} to original type.
package main
import (
"fmt"
"reflect"
)
type AnyType interface{}
func f(a AnyType) AnyType {
return a
}
func main() {
var i32 int32
i32 = 32
var i64 int64
i64 = 64
str := "String"
lst := []AnyType{1, "hello!", []AnyType{1,2,3}}
r1 := f(i32)
t1 := reflect.TypeOf(r1)
fmt.Println(r1)
fmt.Println(t1, t1.Kind() == reflect.Int32, r1.(int32) == i32)
r2 := f(i64)
t2 := reflect.TypeOf(r2)
fmt.Println(r2)
fmt.Println(t2, t2.Kind() == reflect.Int64, r2.(int64) == i64)
r3 := f(str)
t3 := reflect.TypeOf(r3)
fmt.Println(r3)
fmt.Println(t3, r3.(string) == str)
r4 := f(lst)
t4 := reflect.TypeOf(r4)
fmt.Println(r4)
fmt.Println(t4)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment