package main import ( "fmt" "reflect" ) type BaseData struct { // mysql DbUrl string `yaml:"db_url" name:"数据库地址"` DbUser string `yaml:"db_user" name:"数据库用户名"` DbPassWord string `yaml:"db_pass_word" name:"数据库密码"` DbName string `yaml:"db_name" name:"数据库名"` } func main() { d := BaseData{ DbUrl: "url", DbUser: "user", DbPassWord: "pw", DbName: "name", } t := reflect.TypeOf(d) v := reflect.ValueOf(d) for k := 0; k < t.NumField(); k++ { fmt.Println("name:", fmt.Sprintf("%+v", t.Field(k).Name), ", value:", fmt.Sprintf("%v", v.Field(k).Interface()), ", yaml:", t.Field(k).Tag.Get("yaml")) } }
其中可以通过t.Field(k).Name获取struct字段名, 通过v.Field(k).Interface()获取value值, 通过t.Field(k).Tag.Get("yaml")获取标签.
输出内容:
name: DbUrl , value: url , yaml: db_url
name: DbUser , value: user , yaml: db_user
name: DbPassWord , value: pw , yaml: db_pass_word
name: DbName , value: name , yaml: db_name