Golang的指定类型的变量的类型是静态的(也就是指定int、string这些的变量,它的type是static type),在创建变量的时候就已经确定,有静态那么有没有动态呢??
说起动态目前也就只能想起 接口Interface;在Golang的实现中,每个interface变量都有一个对应pair,pair中记录了实际变量的值和类型:(value, type)--value是实际变量值,type是实际变量的类型。一个interface{}类型的变量包含了2个指针,一个指针指向值的类型【对应concrete type】,另外一个指针指向实际的值【对应value】。
什么是反射?
--->反射就是程序能够在运行时检查变量和值,求出它们的类型??------什么意思----??自古以来越是简单描述的东西越难懂,但是理解后又是豁然开朗。
在 Golang中,reflect
实现了运行时反射。reflect
包会帮助识别 interface{}
变量的底层具体类型和具体值。
reflect.Type 和 reflect.Value
reflect.Type
表示 interface{}
的具体类型,而 reflect.Value
表示它的具体值。reflect.TypeOf()
和 reflect.ValueOf()
两个函数可以分别返回 reflect.Type
和 reflect.Value
。这两种类型是我们创建查询生成器的基础;
reflect
包中还有一个重要的类型:Kind
。
在反射包中,Kind
和 Type
的类型可能看起来很相似,
package main
import (
"fmt"
"reflect"
)
type order struct {
ordId int
customerId int
}
func createQuery(q interface{}) {
t := reflect.TypeOf(q)
v := reflect.ValueOf(q)
fmt.Println("Type ", t)
fmt.Println("Value ", v)
}
func createQuery_kind(q interface{}) {
t := reflect.TypeOf(q)
k := t.Kind()
fmt.Println("Type ", t)
fmt.Println("Kind ", k)
}
func main() {
o := order{
ordId: 456,
customerId: 56,
}
createQuery(o)
}
-----------------------------------结果---
Type main.order
Value {456 56}
Type main.order
Kind struct
NumField() 和 Field() 方法
NumField()
方法返回结构体中字段的数量,而 Field(i int)
方法返回字段 i
的 reflect.Value
。
Int() 和 String() 方法
Int
和 String
可以帮助我们分别取出 reflect.Value
作为 int64
和 string
。
http代理服务器(3-4-7层代理)-网络事件库公共组件、内核kernel驱动 摄像头驱动 tcpip网络协议栈、netfilter、bridge 好像看过!!!!
但行好事 莫问前程
--身高体重180的胖子