Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow struct field type to differ from enum type #1804

Open
alexrjones opened this issue May 1, 2024 · 0 comments
Open

feat: Allow struct field type to differ from enum type #1804

alexrjones opened this issue May 1, 2024 · 0 comments

Comments

@alexrjones
Copy link

alexrjones commented May 1, 2024

Is your feature request related to a problem? Please describe.
I have a custom type that functions like an enum. In memory it's a uint32, but in JSON, it's represented as its string value by way of a custom MarshalJSON method:

type MyEnumType uint32

const (
	MyEnumTypeFirst 	= 1
	MyEnumTypeSecond 	= 2
)

func (v MyEnumType) String() string {
	switch v {
	case MyEnumTypeFirst:   return "First"
	case MyEnumTypeSecond:  return "Second"
	}
	return fmt.Sprintf("MyEnumType(%d)", v)
}

func (v MyEnumType) MarshalJSON() ([]byte, error) {

	return []byte("\"" + v.String() + "\""), nil
}

type MyResponse struct {
    MyValue MyEnumType `json:"myValue"`
}

If I try to tag MyResponse.MyValue with enums:"First,Second", I get an error like:

ParseComment error in file ... mypackage.MyResponse: myValue: enum value First can't convert to integer err: strconv.Atoi: parsing "First": invalid syntax

Describe the solution you'd like
Either:

  • allow manually specifying the data type of the enum with a tag. For example, enumType:"string" on an integer type.
  • rather than switching on the struct field type and attempting to marshal it (the current behaviour, ref), try each supported data type in turn, starting with the most likely type and falling back to string if no more specific type exists.

Describe alternatives you've considered
Representing MyEnumType as a string instead would work, but using uint32s with String() string methods to create enums is idiomatic in my project, so this would be a break from convention. It depends whether the maintainers are interested in supporting this behaviour.

Additional context
I'd be happy to do the work to implement this myself but would first like to get input on which of the two solutions (if any) is preferred.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant