Home > Software engineering >  count slice length in struct field
count slice length in struct field

Time:12-02

I think I need a better solution than my case switch as the struct gains more fields my function will become verbose. Is there a way to swap my switch for a loop?

I have the following code

type Things struct {
    StreetNames    []string `json:"streetNames"`
    Letters        []string `json:"letters"`
    MaleNames      []string `json:"maleNames"`
}

func CheckCategories(data *Things, filePath string) error {
    errMsg := "list has no values or is a missing category in File: "   filePath
    categories := []string{"street_name", "letter", "male_first_name"}
    for _, value := range categories {
        switch value {
        case "street_name":
            if len(data.StreetNames) == 0 {
                return errors.New("street_name "   errMsg)
            }
        case "letter":
            if len(data.Letters) == 0 {
                return errors.New("letter "   errMsg)
            }
        case "male_first_name":
            if len(data.MaleNames) == 0 {
                return errors.New("male_first_name "   errMsg)
            }
        }
    }
    return nil
}

This works for me but the real struct contains 12 fields which makes my functions long and repetitive.

I tried

for _, value := range categories {
        if len("data."   value) == 0 {
            return errors.New(value   errMsg)
}

But when I ran the code I took a moment to notice it wasn't working as intended, Im getting the length of the string. I have tried data[value] but that didn't work either.

CodePudding user response:

Is there a way to swap my switch for a loop?

You could do the following:

type Things struct {
    StreetNames []string `json:"streetNames"`
    Letters     []string `json:"letters"`
    MaleNames   []string `json:"maleNames"`
}

func CheckCategories(data *Things, filePath string) error {
    errMsg := "list has no values or is a missing category in File: "   filePath
    categories := []struct{
        name  string
        slice []string
    }{
        {"street_name", data.StreetNames},
        {"letter", data.Letters},
        {"male_first_name", data.MaleNames},
    }

    for _, v := range categories {
        if len(v.slice) == 0 {
            return errors.New(v.name   " "   errMsg)
        }
    }
    return nil
}
  • Related