packagemainimport ("fmt""reflect")funcprintType(v interface{}) { rv := reflect.ValueOf(v) typ := rv.Type() typeName :=""switch rv.Kind() {case reflect.Ptr: typeName ="pointer"case reflect.Int: typeName ="int"case reflect.Int32: typeName ="int32"case reflect.String: typeName ="string"// ... handle more casesdefault: typeName ="unrecognized type" } fmt.Printf("v is of type '%s'. Size: %d bytes\n", typeName, typ.Size())}funcmain() {printType(int32(3))printType("") i :=3printType(&i) // *int i.e. pointer to int}/*---------OUTPUT---------v is of type 'int32'. Size: 4 bytesv is of type 'string'. Size: 16 bytesv is of type 'pointer'. Size: 8 bytes*/
packagemainimport ("fmt""reflect")funcgetIntValue(v interface{}) {var reflectValue = reflect.ValueOf(v) n := reflectValue.Int() fmt.Printf("Int value is: %d\n", n)}funcmain() {getIntValue(3)getIntValue(int8(4))getIntValue("")}/*Int value is: 3Int value is: 4panic: reflect: call of reflect.Value.Int on string Valuegoroutine 1 [running]:reflect.Value.Int(0x111f900, 0x1162920, 0x98, 0x0) /usr/local/go/src/reflect/value.go:986 +0x1a9main.getIntValue(0x111f900, 0x1162920) /Users/ju/gowork/src/test/main.go:24 +0x7emain.main() /Users/ju/gowork/src/test/main.go:31 +0x7bExiting.*/
packagemainimport ("fmt""reflect")typeSstruct { N int}funcsetIntPtr() {var n int=2 reflect.ValueOf(&n).Elem().SetInt(4) fmt.Printf("setIntPtr: n=%d\n", n)}funcsetStructFieldDirect() {var s S reflect.ValueOf(&s.N).Elem().SetInt(5) fmt.Printf("setStructFieldDirect: n=%d\n", s.N)}funcsetStructPtrField() {var s S reflect.ValueOf(&s).Elem().Field(0).SetInt(6) fmt.Printf("setStructPtrField: s.N: %d\n", s.N)}funchandlePanic(funcName string) {if msg :=recover(); msg !=nil { fmt.Printf("%s panicked with '%s'\n", funcName, msg) }}funcsetStructField() {deferhandlePanic("setStructField")var s S reflect.ValueOf(s).Elem().Field(0).SetInt(4) fmt.Printf("s.N: %d\n", s.N)}funcsetInt() {deferhandlePanic("setInt")var n int=2 rv := reflect.ValueOf(n) rv.Elem().SetInt(4)}funcsetIntPtrWithString() {deferhandlePanic("setIntPtrWithString")var n int=2 reflect.ValueOf(&n).Elem().SetString("8")}funcmain() {setIntPtr()setStructFieldDirect()setStructPtrField()setInt()setStructField()setIntPtrWithString()}/*---------OUTPUT-----------setIntPtr: n=4setStructFieldDirect: n=5setStructPtrField: s.N: 6setInt panicked with 'reflect: call of reflect.Value.Elem on int Value'setStructField panicked with 'reflect: call of reflect.Value.Elem on struct Value'setIntPtrWithString panicked with 'reflect: call of reflect.Value.SetString on int Value'*/