enums - handling pointer to constant
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?
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"`
}
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.
Yeah this bit me as well. Seems like the easiest option would be to convert the consts to vars
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