/*
* @description:
*/
/*
* @description:
*/
/*
* @description:
*/
package main
import (
"fmt"
"reflect"
)
func main() {
hh := DBDrive{
Type: "Mysql",
}
sz := 0
switch hh.Type {
case "Badger":
sz = hh.Badger.GetGlobalObj()
default:
sz = hh.Mysql.GetGlobalObj()
}
fmt.Println(sz)
useReflect(hh, hh.Type, "GetGlobalObj")
}
type DBDrive struct {
Type string
Mysql Mysql
Badger Badger
}
type Mysql struct{}
func (m Mysql) GetGlobalObj() int {
fmt.Println("mysql func")
return 1
}
type Badger struct {
Badger2
}
func (b Badger) GetGlobalObj() int {
fmt.Println("badger func")
return 2
}
type Badger2 struct {
}
func (b Badger2) GetGlobalObj2() (int, string) {
fmt.Println("badger2 func")
return 9, "ok"
}
// inter一个嵌套结构体
func useReflect(inter interface{}, attributeName, method string) {
v := reflect.ValueOf(inter)
dbObj := v.FieldByName(attributeName) // 根据字段名获取属性 // 获得struct inter内嵌套的struct attributeName
m := dbObj.MethodByName(method) // 获取 struct attributeName的method方法
result := m.Call([]reflect.Value{}) // 调用struct attributeName的method方法 m.Call([]reflect.Value{reflect.ValueOf("参数值")})
fmt.Println(result) // 函数返回的值
for k, v := range result {
fmt.Println(k, v) // 函数的返回值
}
}
go嵌套结构体
最新推荐文章于 2023-10-26 14:23:54 发布