golang:通过reflect取struct的字段长度,手动取结构体tag与name的对应关系

type Config struct {
        Listen       string `json:"listen" toml:"listen"`
        UserAPIURL   string `json:"userapisrv" toml:"userAPIURL"`
        SecretKey    string `json:"secret_key" toml:"secret_key"`
        AuthorityUrl string `json:"authorityapisrv" toml:"authority_url"`
        ResourceKey  string `json:"resource_key" toml:"resource_key"`
    }
    c := &Config{}

    cvalue := reflect.ValueOf(c)

    l := cvalue.Elem().NumField()
c := &Config{}

cType := reflect.TypeOf(c)

cValue := reflect.ValueOf(c)

structLen := cValue.Elem().NumField()

structMap := make(map[string]string, structLen)

for i := 0; i < structLen; i++ {
    field := cType.Elem().Field(i)
    jsonName := field.Tag.Get("json")
    structMap[jsonName] = field.Name
}

猜你喜欢

转载自blog.csdn.net/keyunq/article/details/80846783