在实际工程中,虽然使用reflect会影响性能并且降低代码的可读性,但是reflect能做到代码的动态性和灵活性,因此也被工程上广泛使用,接下里列举几个reflect的应用示例
1. 实现通用的数据序列化和反序列化
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func serialize(obj interface{
}) ([]byte, error) {
value := reflect.ValueOf(obj)
if value.Kind()!= reflect.Struct {
return nil, fmt.Errorf("input is not a struct")
}
data := make(map[string]interface{
})
typeOfObj := value.Type()
for i := 0; i < value.NumField(); i