宜昌建网站,凡科网站建设网站,怎样做网店生意,高端营销型企业网站建设package main
import ( “fmt” “reflect”
)
type Job interface { New([]interface{}) interface{} Run() (interface{}, error) }
type DetEd struct { Name string Age int }
// 为什么这样设计 // 这样就避免了 在创建新的实例的之后 结构体的方法中接受者为指针类型…package main
import ( “fmt” “reflect”
)
type Job interface { New([]interface{}) interface{} Run() (interface{}, error) }
type DetEd struct { Name string Age int }
// 为什么这样设计 // 这样就避免了 在创建新的实例的之后 结构体的方法中接受者为指针类型的不可见的问题 func (DetEd) New() *DetEd { return DetEd{} }
func (ed *DetEd) Run(msg int) (interface{}, error) { fmt.Printf(“msg %v,name%v, age%v \n”, msg, ed.Name, ed.Age) return nil, nil }
func CreateNewObject(controller interface{}) { // 解析结构体 Dt : reflect.TypeOf(controller) // 这里可以拿到两个方法
_, ok : Dt.MethodByName(New)
if !ok {panic(not found New function)
}Dt Dt.Elem() // 这之后就只能拿到一个方法了
// 记录对应属性所在的位置
nameMap : make(map[int]string, 0)
for i : 0; i Dt.NumField(); i {field : Dt.Field(i)nameMap[i] field.Name
}// 创建新的指针结构体对象
// 获取一个新的结构体对象
rv : reflect.ValueOf(controller)
newobjects : rv.MethodByName(New).Call(nil)
targetObject : newobjects[0]
// targetObject.newDATA : targetObject.Interface().(*DetEd)
newDATA.Run(111111111111111)// 真实数据 赋值
// tObject : targetObject.Elem() // 获取真实数据
// idata : map[string]interface{}{Name: 张三, Age: 23}
// for i : 0; i tObject.NumField(); i {
// field : tObject.Field(i)
// fieldType : field.Type()
// targetValue : reflect.ValueOf(idata[nameMap[i]])
// // 将输入的值转换为结构体对应属性需要的类型
// result : reflect.ValueOf(targetValue.Interface()).Convert(fieldType)
// // 赋值
// tObject.Field(i).Set(result)
// }
// // 运行指定方法
// targetObject.MethodByName(Run).Call([]reflect.Value{1})}
type OperatorInterface interface { New(conf []byte) (OperatorInterface, error) Run() }
type MergeOPNew struct { Conf struct { Enabled bool yaml:enabled } Data string }
// New 通过反射创建出新一个对象 func (op *MergeOPNew) New(data []byte) (result OperatorInterface, err error) { tmpResult : MergeOPNew{Data: “3”}
return tmpResult, nil}
func (op *MergeOPNew) Run() { fmt.Printf(“Run %s\n”, op.Data) }
func main() { mergeOPNew : MergeOPNew{} data, err : mergeOPNew.New([]byte(enabled: true)) if err ! nil { panic(err) } data.Run() // CreateNewObject(DetEd{})
// []strategy.MergeOPV3}
type Student struct { Id int Name string Age int }
func reflectTest(i interface{}) { // 获取变量的 reflect.Type reType : reflect.TypeOf(i) fmt.Println(“reflect.Type”, reType)
// 获取变量的 reflect.Value
reVal : reflect.ValueOf(i)
fmt.Println(reflect.Value, reVal)// 打印reVal类型使用 reVal打印Name 成员 失败。无法索引Name成员
//fmt.Printf(reVal%T, name%v,reVal, reVal.Name)// 将 reVal 转成 interface
iVal : reVal.Interface()
fmt.Printf(iVal %v, type %T\n, iVal, iVal)
// iVal.Name 会报错Unresolved reference Name
// fmt.Printf(iVal %v, type %T, name %v\n, iVal, iVal, iVal.Name)// 将 interface 通过类型断言 转回成 Student
// stu: iVal.(Student)
if stu, ok : iVal.(Student); ok {fmt.Printf(stu %v, type %T, name%v\n, stu, stu, stu.Name)
}}