企业电子商务网站建设的必要性,佛山营销网站建设推广,韩国有哪些专业做汽车的网站?,深圳科技公司黄页文章目录 demo1 数据类型判断demo2 打印任意类型数据 demo1 数据类型判断
使用reflect.TypeOf()方法打印go中数据类型#xff0c;可参考go官方API文档;使用格式化参数%T也能打印数据类型。
package mainimport fmt
import reflect
import io可参考go官方API文档;使用格式化参数%T也能打印数据类型。
package mainimport fmt
import reflect
import io
import osfunc main() {TypeTest()
}func TypeTest() {tInt : reflect.TypeOf(3) // inttStr : reflect.TypeOf(文字) // stringtBool : reflect.TypeOf(true) // booltFloat : reflect.TypeOf(3.14) // float64tSlice : reflect.TypeOf([]int{1, 2}) // []inttMap : reflect.TypeOf(map[int]string{}) // map[int]stringvar w io.Writer os.Stdout // *os.FiletW : reflect.TypeOf(w)fmt.Println(tInt, tStr, tBool, tFloat, tSlice, tMap, tW)fmt.Printf(%T %T %T %T %T %T %T, 3, feng, true, 3.14, []int{1, 2}, map[int]string{}, os.Stdout)
}输出
int string bool float64 []int map[int]string *os.File
int string bool float64 []int map[int]string *os.Filedemo2 打印任意类型数据
开始写代码之前简单了解一些reflect包中的结构体和方法。
1.结构体reflect.Value类型数据指针
type Value struct {typ *rtypeptr unsafe.Pointerflag
}
type flag uintptr2.方法reflect.ValueOf() 入参接口interface{}也就是任意类型 出参reflect.Value结构体
func ValueOf(i any) Value {if i nil {return Value{}}escapes(i)return unpackEface(i)
}3.方法reflect.Value{}.Interface() 将Value的数据值转为interface{}类型
func (v Value) Interface() (i any) {return valueInterface(v, true)
}4.类型reflect.Kind 实际上Kind是一个uint类型的别名使用Kind类型定义了go中各种数据类型枚举如下 iota变量是0常量块定义中使用iota后面的如果没有指定数值一般就是自增
type Kind uintconst (Invalid Kind iotaBoolIntInt8Int16Int32Int64UintUint8Uint16Uint32Uint64UintptrFloat32Float64Complex64Complex128ArrayChanFuncInterfaceMapPointerSliceStringStructUnsafePointer
)结构体reflect.Type数据类型
type Type interface {// 对齐方式Align() int// 结构体字段的对齐方式FieldAlign() int// 从方法集合中返回索引为i的方法Method(int) Method// 通过方法名在方法集合中找方法返回方法和是否找到的bool类型结果MethodByName(string) (Method, bool)// 返回方法数量NumMethod() int// 返回类型的名称例如 int、string等Name() string// 返回包路径例如encoding/base64PkgPath() string// 返回类型大小比如int占8字节Size() uintptr// 返回最段的类型例如”base64“而不是encoding/base64String() string// 返回类型的数字枚举Kind() Kind// 返回u类型是否实现了接口Implements(u Type) bool// 当前类型的值是否可以赋值为u类型AssignableTo(u Type) bool// 当前类型的值是否可以转换为u类型就算可转换依然可能会panic。比如数组大小不匹配时进行转换ConvertibleTo(u Type) bool// 此类型是否可比较返回true在比较时也可能panic因为interface是可比较的但是interface的子类可能是不可比较的Comparable() boolBits() intChanDir() ChanDirIsVariadic() bool// 返回此类型的元素类型必须是Array、Chan、Map、Pointer、Slice类型调用否则会panicElem() Type// 返回索引为i的结构体类型的字段Field(i int) StructField// 必须是结构体调用否则会panic。返回嵌套字段FieldByIndex(index []int) StructField// 根据名字获取字段找到返回trueFieldByName(name string) (StructField, bool)// 根据条件查找字段FieldByNameFunc(match func(string) bool) (StructField, bool)// In returns the type of a function types ith input parameter.// It panics if the types Kind is not Func.// It panics if i is not in the range [0, NumIn()).In(i int) Type// Key returns a map types key type.// It panics if the types Kind is not Map.Key() Type// Len returns an array types length.// It panics if the types Kind is not Array.Len() int// NumField returns a struct types field count.// It panics if the types Kind is not Struct.NumField() int// NumIn returns a function types input parameter count.// It panics if the types Kind is not Func.NumIn() int// NumOut returns a function types output parameter count.// It panics if the types Kind is not Func.NumOut() int// Out returns the type of a function types ith output parameter.// It panics if the types Kind is not Func.// It panics if i is not in the range [0, NumOut()).Out(i int) Typecommon() *rtypeuncommon() *uncommonType
}了解反射包下的基本数据结构和方法后下面开始编程
package mainimport (fmtreflectstrconv
)// 任何类型转打印
func AnyToString(a interface{}) string {// v是Value类型属性包含a的实际类型值v : reflect.ValueOf(a)// 判断v的类型switch v.Kind() {case reflect.Invalid: // 无效值return invalidcase reflect.String: // 字符串return v.String()case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: // 数字类型return strconv.FormatInt(v.Int(), 10)case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: // 无符号数字类型return strconv.FormatUint(v.Uint(), 10)case reflect.Bool: // 布尔类型return strconv.FormatBool(v.Bool())case reflect.Float64, reflect.Float32: // 浮点数类型return strconv.FormatFloat(v.Float(), f, -1, 64)case reflect.Ptr: // 指针类型if v.IsNil() {return nil}// v.Elem()取出指针指向的数据类型为reflect.Value// v.Elem().Interface()将reflect.Value转为interface{}// AnyToString(v.Elem().Interface()) 递归再次获取字符串return AnyToString(v.Elem().Interface())case reflect.Slice, reflect.Array: // 切片和数组类型s : [// 获取数组或者切片的长度length : v.Len()for i : 0; i length; i {// v.Index(i)为获取下标为i的reflect.Value类型数据// v.Index(i).Interface() 将reflect.Value转为interface{}// AnyToString(v.Index(i).Interface()) 递归再次获取字符串s AnyToString(v.Index(i).Interface())if i length-1 {s ,}}s ]return scase reflect.Map: // 字典类型// 反射获取map的所有keykeys : v.MapKeys()// 获取map的长度length : len(keys)s : {for i : 0; i length; i {key : keys[i]// 获取map的valuevalue : v.MapIndex(key)s fmt.Sprintf(%s, AnyToString(key.Interface())) // 拼接keys : s AnyToString(value.Interface()) // 拼接valueif i length-1 {s , }}s }return scase reflect.Struct: // 结构体类型s : {count : v.NumField() // 获取结构体的字段数量for i : 0; i count; i {// v.Type().Field(i) s fmt.Sprintf(%s:%s, v.Type().Field(i).Name, AnyToString(v.Field(i).Interface()))if i count-1 {s ,}}s }return sdefault: // 其他类型return fmt.Sprintf(%v, v)}
}func main() {fmt.Println(AnyToString(1))fmt.Println(AnyToString(字符串))fmt.Println(AnyToString(3.1415926))fmt.Println(AnyToString(255))fmt.Println(AnyToString([]int{1, 2, 3}))fmt.Println(AnyToString(map[string]int{age: 1}))account : Account{Age: 2,Name: jinnian,}accountList : []Account{{1, wo},{0, c},}fmt.Println(AnyToString(accountList))fmt.Println(AnyToString(account))fmt.Println(AnyToString(nil))fmt.Println(AnyToString(true))fmt.Println(AnyToString(accountList))
}输出
1
字符串
3.1415926
255
[1,2,3]
{age: 1}
[{Age:1,Name:wo},{Age:0,Name:c}]
{Age:2,Name:jinnian}
invalid
true
[{Age:1,Name:wo},{Age:0,Name:c}]开始学起来吧