github.com/bobyang007/helper@v1.1.3/reflecth/utils.go (about) 1 package reflecth 2 3 import ( 4 "github.com/bobyang007/helper/goh/asth" 5 "go/ast" 6 "reflect" 7 ) 8 9 // TypeOfPtr returns type of value pointed to by i. 10 // If i is not a pointer than TypeOfPtr returns nil. 11 func TypeOfPtr(i interface{}) reflect.Type { 12 t := reflect.TypeOf(i) 13 if t.Kind() != reflect.Ptr { 14 return nil 15 } 16 return t.Elem() 17 } 18 19 // ValueOfPtr returns value pointed to by i. 20 // If i is not a pointer than ValueOfPtr returns zero Value. 21 // This function is useful for passing interface to reflect.Value via passing pointer to interface to this function (it is impossible to make reflect.Value of kind interface via passing interface directly to ValueOf function). 22 func ValueOfPtr(i interface{}) reflect.Value { 23 r := reflect.ValueOf(i) 24 if r.Type().Kind() != reflect.Ptr { 25 return reflect.Value{} 26 } 27 return r.Elem() 28 } 29 30 // ChanDirFromAst preforms conversion channel direction from ast.ChanDir representation to reflect.ChanDir representation. 31 // ChanDirFromAst returns 0 if dir cannot be represented as reflect.ChanDir (if dir invalid itself). 32 func ChanDirFromAst(dir ast.ChanDir) (r reflect.ChanDir) { 33 switch dir { 34 case asth.SendDir: 35 return reflect.SendDir 36 case asth.RecvDir: 37 return reflect.RecvDir 38 case asth.BothDir: 39 return reflect.BothDir 40 default: 41 return 0 42 } 43 } 44 45 // ChanDirToAst preforms conversion channel direction from reflect.ChanDir representation to ast.ChanDir representation. 46 // ChanDirToAst returns 0 if dir cannot be represented as ast.ChanDir (if dir invalid itself). 47 func ChanDirToAst(dir reflect.ChanDir) (r ast.ChanDir) { 48 switch dir { 49 case reflect.SendDir: 50 return asth.SendDir 51 case reflect.RecvDir: 52 return asth.RecvDir 53 case reflect.BothDir: 54 return asth.BothDir 55 default: 56 return 0 57 } 58 }