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*/
package main
import (
"fmt"
"reflect"
)
func getIntValue(v interface{}) {
var reflectValue = reflect.ValueOf(v)
n := reflectValue.Int()
fmt.Printf("Int value is: %d\n", n)
}
func main() {
getIntValue(3)
getIntValue(int8(4))
getIntValue("")
}
/*
Int value is: 3
Int value is: 4
panic: reflect: call of reflect.Value.Int on string Value
goroutine 1 [running]:
reflect.Value.Int(0x111f900, 0x1162920, 0x98, 0x0)
/usr/local/go/src/reflect/value.go:986 +0x1a9
main.getIntValue(0x111f900, 0x1162920)
/Users/ju/gowork/src/test/main.go:24 +0x7e
main.main()
/Users/ju/gowork/src/test/main.go:31 +0x7b
Exiting.
*/
package main
import (
"fmt"
"reflect"
)
type S struct {
N int
}
func setIntPtr() {
var n int = 2
reflect.ValueOf(&n).Elem().SetInt(4)
fmt.Printf("setIntPtr: n=%d\n", n)
}
func setStructFieldDirect() {
var s S
reflect.ValueOf(&s.N).Elem().SetInt(5)
fmt.Printf("setStructFieldDirect: n=%d\n", s.N)
}
func setStructPtrField() {
var s S
reflect.ValueOf(&s).Elem().Field(0).SetInt(6)
fmt.Printf("setStructPtrField: s.N: %d\n", s.N)
}
func handlePanic(funcName string) {
if msg := recover(); msg != nil {
fmt.Printf("%s panicked with '%s'\n", funcName, msg)
}
}
func setStructField() {
defer handlePanic("setStructField")
var s S
reflect.ValueOf(s).Elem().Field(0).SetInt(4)
fmt.Printf("s.N: %d\n", s.N)
}
func setInt() {
defer handlePanic("setInt")
var n int = 2
rv := reflect.ValueOf(n)
rv.Elem().SetInt(4)
}
func setIntPtrWithString() {
defer handlePanic("setIntPtrWithString")
var n int = 2
reflect.ValueOf(&n).Elem().SetString("8")
}
func main() {
setIntPtr()
setStructFieldDirect()
setStructPtrField()
setInt()
setStructField()
setIntPtrWithString()
}
/*
---------OUTPUT-----------
setIntPtr: n=4
setStructFieldDirect: n=5
setStructPtrField: s.N: 6
setInt 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'
*/