oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

enums - handling pointer to constant

Open RuiLoureiro opened this issue 4 years ago • 4 comments

Suppose I have the following model definition in my api.yaml:

components:
  schemas:
    MyModel:
      title: My model
      properties:
        status:
          type: string
          enum:
            - PENDING
            - COMPLETED

With the recent enum changes, this will generate the following code:

// Defines values for MyModelStatus.
const (
	MyModelStatusCOMPLETED MyModelStatus = "COMPLETED"

	MyModelStatusPENDING MyModelStatus = "PENDING"
)

// MyModel defines model for MyModel.
type MyModel struct {
	Status *MyModelStatus `json:"status,omitempty"`
}

// MyModelStatus defines model for MyModel.Status.
type MyModelStatus string

When I need to initialize a struct of type MyModel, I would like to do something like:

my_model := MyModel{
	Status: &MyModelStatusCOMPLETED,
}

Since in go you can't take the address of a const, I have to do something like what's described in this SO thread:

const k = MyModelStatusCOMPLETED
v := k
my_model := MyModel{
	Status: &v
}

Is there any workaround that I'm unaware of?

RuiLoureiro avatar May 12 '21 16:05 RuiLoureiro

You could make the status property required so it will be generated like below instead but that could cause other issue for you down the road if you need it to be nil at some point

type MyModel struct {
	Status MyModelStatus `json:"status,omitempty"`
}

smcgowan-smartsheet avatar May 14 '21 16:05 smcgowan-smartsheet

You could make the status property required so it will be generated like below instead but that could cause other issue for you down the road if you need it to be nil at some point

type MyModel struct {
	Status MyModelStatus `json:"status,omitempty"`
}

Thank you for your reply, but I need to have optional enum properties.

RuiLoureiro avatar May 18 '21 09:05 RuiLoureiro

Yeah this bit me as well. Seems like the easiest option would be to convert the consts to vars

discordianfish avatar Sep 28 '22 15:09 discordianfish

Now we're on Go 1.18 we have access to generics, and could add (via):

func PtrTo[T any](v T) *T {
  return &v
}

This means we don't need to relax the const to a var

jamietanna avatar Nov 23 '22 09:11 jamietanna