go嵌套结构体

/*
 * @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) // 函数的返回值
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值