• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

golang Iterate through the fields of a struct in Go

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
package main

import (
	"fmt"
	"reflect"
)

type Log struct {
	Path  string
	Level string
}

func (l *Log) Conversion(i interface{}) {

	if data, ok := i.(*Log); ok {
		if data != nil {
			if len(data.Path) > 0 {
				l.Path = data.Path
			}
			if len(data.Level) > 0 {
				l.Level = data.Level
			}
		}
	}
}

type Storage struct {
	Type       string
	ServerList []string
}

func (s *Storage) Conversion(i interface{}) {

	if data, ok := i.(*Storage); ok {
		if data != nil {
			if len(data.Type) > 0 {
				s.Type = data.Type
			}
		}
	}
}

type Server struct {
	LogConfig     *Log
	StorageConfig *Storage
}

func main() {
	def := Server{
		LogConfig: &Log{
			Path:  "/your/old/log/path/",
			Level: "info",
		},
		StorageConfig: &Storage{
			Type:       "zookeeper",
			ServerList: []string{"127.0.0.1:2181"},
		},
	}
	fmt.Println(def)
	cur := Server{
		LogConfig: &Log{
			Path:  "/your/new/log/path/",
			Level: "debug",
		},
		StorageConfig: &Storage{
			Type:       "etcd",
			ServerList: []string{"127.0.0.1:2379"},
		},
	}

	fmt.Println(cur)

	defV := reflect.ValueOf(def)
	curV := reflect.ValueOf(cur)
	for k := 0; k < defV.NumField(); k++ {
		in := make([]reflect.Value, 1)
		in[0] = reflect.ValueOf(curV.Field(k).Interface())
		defV.Field(k).MethodByName("Conversion").Call(in)
	}

	fmt.Println(def.LogConfig)
	fmt.Println(def.StorageConfig)
}

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go语言规格说明书 之 结构体类型(Struct types)发布时间:2022-07-10
下一篇:
Go 有望成为云端应用开发的首选语言!发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap