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:
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)