Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go Reflection Get current field name but get errors around mismatched types untyped string

type Issue struct {
  SysId  uuid.UUID  `json:"sysid" maelstrom:"required"`
}

func (i *Issue) Unmarshal(data []byte) error {
  err := json.Unmarshal(data, i)
  if err != nil {
    slog.Error(err.Error())
    return err
  }
  fields := reflect.ValueOf(i).Elem()
  for i := 0; i < fields.NumField(); i++ {
    maelstromTags := fields.Type().Field(i).Tag.Get("maelstrom")
    if strings.Contains(maelstromTags, "required") && fields.Field(i).IsZero() {
      return errors.New("Required field is missing." + fields.Field(i))
    }
  }
  return nil
}

In the code above, on the line:

return errors.New("Required field is missing." + fields.Field(i))

I want to include the current field’s name in the error message.

Here is the error I’m getting:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

invalid operation: "Required field is missing." + fields.Field(i) (mismatched types untyped string and reflect.Value)

I’ve also tried this:

return errors.New("Required field is missing." + fields.Field(i).String)

But I get this:

invalid operation: "Required field is missing." + fields.Field(i).String (mismatched types untyped string and func() string)

I’ve also tried this:

return errors.New("Required field is missing." + string(fields.Field(i)))

But I get this:

cannot convert fields.Field(i) (value of type reflect.Value) to type string [InvalidConversion]

Can someone point me in the right direction or offer a solution? Thanks!

>Solution :

Get the StructField from the type. Get the field name from the StructType.

return fmt.Errorf("required field is missing: %s", fields.Type().Field(i).Name)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading