本文主要是介绍golang基础-反射获取(基础数据、结构体)、操作(基本类型、结构体、指针)、反射获取Tag,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
-
-
- 反射获取基本类型
- 反射获取结构体
- Elem反射操作基本类型
- 反射调用结构体方法
- Elem反射操作结构体
- Elem反射获取tag
- 练习例子
-
-
反射获取基本类型
反射:可以在运行时动态获取变量的相关信息
Import (“reflect”)
a. reflect.TypeOf,获取变量的类型,返回reflect.Type类型
b. reflect.ValueOf,获取变量的值,返回reflect.Value类型
c. reflect.Value.Kind,获取变量的类别,返回一个常量
d. reflect.Value.Interface(),转换成interface{}类型
var x float64 = 3.4fmt.Println("type:", reflect.TypeOf(x))v := reflect.ValueOf(x)fmt.Println("value:", v)fmt.Println("type:", v.Type())fmt.Println("kind:", v.Kind())fmt.Println("value:", v.Float())fmt.Println(v.Interface())fmt.Printf("value is %5.2e\n", v.Interface())y := v.Interface().(float64)fmt.Println(y)
输出如下:
type: float64
value: 3.4
type: float64
kind: float64
value: 3.4
3.4
value is 3.40e+00
3.4
反射获取结构体
package mainimport ("fmt""reflect"
)type Student struct {Name stringAge intScore float32
}func test(b interface{}) {t := reflect.TypeOf(b)fmt.Println(t)v := reflect.ValueOf(b)fmt.Println(v)k := v.Kind()fmt.Println(k)iv := v.Interface()fmt.Println(iv)stu, ok := iv.(Student)if ok {fmt.Printf("%v %T\n", stu, stu)}
}func main() {var a Student = Student{Name: "stu01",Age: 18,Score: 92,}test(a)
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
main.Student
{stu01 18 92}
struct
{stu01 18 92}
{stu01 18 92} main.Student
PS E:\golang\go_pro\src\safly>
Elem反射操作基本类型
用来获取指针指向的变量,相当于:
var a *int;
func main() {var b int = 1b = 200testInt(&b)fmt.Println(b)
}//fv.Elem()用来获取指针指向的变量
func testInt(b interface{}) {val := reflect.ValueOf(b)val.Elem().SetInt(100)c := val.Elem().Int()fmt.Printf("get value interface{} %d\n", c)fmt.Printf("string val:%d\n", val.Elem().Int())
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
get value interface{} 100
string val:100
100
PS E:\golang\go_pro\src\safly>
反射调用结构体方法
package mainimport ("fmt""reflect"
)type Student struct {Name stringAge intScore float32}func (s Student) Print(){fmt.Println(s)
}func (s Student) Set(name string,age int,score float32){s.Age = ages.Name = names.Score = score
}func TestStruct(a interface{}) {val := reflect.ValueOf(a)kd := val.Kind()fmt.Println(val,kd)if kd != reflect.Struct {fmt.Println("expect struct")return}//获取字段数量fields:= val.NumField()fmt.Printf("struct has %d field\n",fields)//获取字段的类型for i:=0;i<fields;i++{fmt.Printf("%d %v\n",i,val.Field(i).Kind())}//获取方法数量methods:=val.NumMethod()fmt.Printf("struct has %d methods\n",methods)//反射调用的Print方法var params []reflect.Valueval.Method(0).Call(params)}func main() {var a Student = Student{Name: "stu01",Age: 18,Score: 92.8,}TestStruct(a)// fmt.Println(a)
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
{stu01 18 92.8} struct
struct has 3 field
0 string
1 int
2 float32
struct has 2 methods
{stu01 18 92.8}
PS E:\golang\go_pro\src\safly>
Elem反射操作结构体
package mainimport ("fmt""reflect"
)type Student struct {Name stringAge intScore float32}func (s Student) Print(){fmt.Println(s)
}func (s Student) Set(name string,age int,score float32){s.Age = ages.Name = names.Score = score
}func TestStruct(a interface{}) {val := reflect.ValueOf(a)kd := val.Kind()fmt.Println(val,kd)if kd!= reflect.Ptr && val.Elem().Kind() == reflect.Struct {fmt.Println("expect struct")return}//获取字段数量fields:= val.Elem().NumField()fmt.Printf("struct has %d field\n",fields)//获取字段的类型for i:=0;i<fields;i++{fmt.Printf("%d %v\n",i,val.Elem().Field(i).Kind())}//获取方法数量methods:=val.NumMethod()fmt.Printf("struct has %d methods\n",methods)//反射调用的Print方法var params []reflect.Valueval.Elem().Method(0).Call(params)
}func main() {var a Student = Student{Name: "stu01",Age: 18,Score: 92.8,}TestStruct(&a)// fmt.Println(a)
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
&{stu01 18 92.8} ptr
struct has 3 field
0 string
1 int
2 float32
struct has 2 methods
{stu01 18 92.8}
PS E:\golang\go_pro\src\safly>
Elem反射获取tag
package mainimport ("fmt""reflect"
)type Student struct {Name string `json:"stu_name"`Age intScore float32}func (s Student) Print(){fmt.Println(s)
}func (s Student) Set(name string,age int,score float32){s.Age = ages.Name = names.Score = score
}func TestStruct(a interface{}) {typ := reflect.TypeOf(a)tag := typ.Elem().Field(0).Tag.Get("json")fmt.Printf("Tag:%s\n",tag)
}func main() {var a Student = Student{Name: "stu01",Age: 18,Score: 92.8,}TestStruct(&a)
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
Tag:stu_name
PS E:\golang\go_pro\src\safly>
练习例子
package mainimport ("fmt""reflect"
)type T struct {A intB string
}func main() {t := T{23, "skidoo"}s := reflect.ValueOf(&t).Elem()typeOfT := s.Type()for i := 0; i < s.NumField(); i++ {f := s.Field(i)fmt.Printf("%d: %s %s = %v\n", i,typeOfT.Field(i).Name, f.Type(), f.Interface())}s.Field(0).SetInt(77)s.Field(1).SetString("Sunset Strip")fmt.Println("t is now", t)
}
输出如下:
PS E:\golang\go_pro\src\safly> go run demo.go
0: A int = 23
1: B string = skidoo
t is now {77 Sunset Strip}
PS E:\golang\go_pro\src\safly>
这篇关于golang基础-反射获取(基础数据、结构体)、操作(基本类型、结构体、指针)、反射获取Tag的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!