Golang变量结构
变量由 type 与 value 两部分构成,其中 type 分为 static type 与 concrete type,将 type 与value 称为 pair 对。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| func main() {
a:="string"
var allType interface{}
allType=a str,_:=allType.(string)
fmt.Println(str)
}
|
pair 对中,type 与 value 本质上为两个指针,分别指向变量的值与类型。
反射机制reflect
使用反射机制,易于动态获取变量的类型(Type)。
reflect包提供两个重要接口: ValueOf 与 TypeOf 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import "reflect"
func reflectNum(arg interface{}){ fmt.Println("type:",reflect.TypeOf(arg)) fmt.Println("value:",reflect.ValueOf(arg)) }
func main() { var num float64=1.2345 reflectNum(num) }
float64 1.2345
|
同样的,可以使用这两个接口获取结构体中的类型与值,或获取type中的字段与方法。
将结构体中的字段称作Field,例如其中的 name string 即为一个field。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| type person struct{ name string age int sex string }
func GetField(input interface{}){ inputType:=reflect.TypeOf(input) for i:=0;i<inputType.NumField();i++{ field:=inputType.Field(i) fmt.Printf("%s:%v\n",field.Name,field.Type) } }
func GetMethod(input interface{}){ inputType:=reflect.TypeOf(input) for i:=0;i<inputType.NumMethod();i++{ method:=inputType.Method(i) fmt.Printf("%s:%v\n",method.Name,method.Type) } }
|
结构体标签
使用 `` 可以为结构体编写标签,通过reflect接口,能够访问所编写的标签。
1 2 3 4 5
| type person struct{ name string `info:"name" doc:"我的名字"` age int `info:"年龄"` sex string `info:"性别"` }
|
对field调用Tag.Get(“标签名”),以得到标签信息。
1 2 3 4 5 6 7 8
| func findTag(str interface{}){
t:=reflect.TypeOf(str).Elem() for i:=0;i<t.NumField();i++{ ts:=t.Field(i).Tag.Get("info") fmt.Println("info:",ts) } }
|