golang之反射和断言的具体使用
- 作者: 嘻嘻哈哈嘿嘿呵呵吼吼
- 来源: 51数据库
- 2021-08-03
1. 反射
反射这个概念绝大多数语言都有,比如java,php之类,golang自然也不例外,反射其实程序能够自描述和自控制的一类机制。
比如,通过php的反射,你可以知道一个类有什么成员,有什么方法。而golang,也能够通过官方自带的reflect包来了解各种变量类型及其信息。
下面我们通过一个例子查看反射的基本用法。
话不多说,直接贴代码:
package main
import (
"fmt"
"reflect"
)
type order struct {
ordid int `json:"order_id" validate:"required"`
customerid string `json:"customer_id" validate:"required"`
callback func() `json:"call_back" validate:"required"`
}
func reflectinfo(q interface{}) {
t := reflect.typeof(q)
v := reflect.valueof(q)
fmt.println("type ", t)
fmt.println("value ", v)
for i := 0; i < v.numfield(); i = i + 1 {
fv := v.field(i)
ft := t.field(i)
tag := t.field(i).tag.get("json")
validate := t.field(i).tag.get("validate")
switch fv.kind() {
case reflect.string:
fmt.printf("the %d th %s types: %s, valuing: %s, struct tag: %v\n", i, ft.name, "string", fv.string(), tag + " " + validate)
case reflect.int:
fmt.printf("the %d th %s types %s, valuing %d, struct tag: %v\n", i, ft.name, "int", fv.int(), tag + " " + validate)
case reflect.func:
fmt.printf("the %d th %s types %s, valuing %v, struct tag: %v\n", i, ft.name, "func", fv.string(), tag + " " + validate)
}
}
}
func main() {
o := order{
ordid: 456,
customerid: "39e9e709-dd4f-0512-9488-a67c508b170f",
}
reflectinfo(o)
}
首先,我们用reflect.typeof(q)和reflect.valueof(q)获取了结构体order的类型和值,然后我们再从循环里对它的成员进行一个遍历,并将所有成员的名称和类型打印了出来。这样,一个结构体的所有信息就都暴露在我们面前。
2.断言
go语言里面有一个语法,可以直接判断是否是该类型的变量: value, ok = element.(t),这里value就是变量的值,ok是一个bool类型,element是interface变量,t是断言的类型。
如果element里面确实存储了t类型的数值,那么ok返回true,否则返回false。
package main
import (
"fmt"
)
type order struct {
ordid int
customerid int
callback func()
}
func main() {
var i interface{}
i = order{
ordid: 456,
customerid: 56,
}
value, ok := i.(order)
if !ok {
fmt.println("it's not ok for type order")
return
}
fmt.println("the value is ", value)
}
输出:
the value is {456 56 <nil>}
常见的还有用switch来断言:
package main
import (
"fmt"
)
type order struct {
ordid int
customerid int
callback func()
}
func main() {
var i interface{}
i = order{
ordid: 456,
customerid: 56,
}
switch value := i.(type) {
case int:
fmt.printf("it is an int and its value is %d\n", value)
case string:
fmt.printf("it is a string and its value is %s\n", value)
case order:
fmt.printf("it is a order and its value is %v\n", value)
default:
fmt.println("it is of a different type")
}
}
输出:
it is a order and its value is {456 56 <nil>}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读
