-
Notifications
You must be signed in to change notification settings - Fork 91
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
Optional Fields: Should NewOptType(v) take a pointer instead? #1274
Comments
I use this approach, for nil values. func TestNilToVal(t *testing.T) {
var boolean *bool
resBool := ogencl.NewOptBool(NilToVal(boolean))
fmt.Println(resBool)
var str *string
resString := ogencl.NewOptString(NilToVal(str))
fmt.Println(resString)
}
func NilToVal[T any](v *T) T {
if v == nil {
v = new(T)
}
return *v
} |
@wildwind123 That approach makes the assumption that If you do that with a
which does not have the same meaning as:
|
Just wanted to bump this up as I have also just ran into a similar issue with |
I don't think it makes sense that It makes things boilerplate, and error prone if you don't understand well how the ogen schemas work: // This is returned from another abstracted layer, that doesn't know anything about http/openapi
servideModel := myService.ActionThatReturnsModel(...)
modelField := OptNilModelField{} // Type generated by ogen
// The field is a pointer in the service, and may be nil.
if servideModel.Field == nil {
modelField.SetToNull()
} else {
modelField.SetTo(*servideModel.Field)
}
return &Model{
Field: modelField,
}, nil Proposal / IdeaI think the code of // Currently generated by ogen.
//
// func NewOptNilModelField(v Model) OptNilModelField {
// return OptNilModelField{
// Value: v,
// Set: true,
// }
// }
// Proposed replacement
func NewOptNilModelField(v *Model) OptNilModelField {
if v == nil {
return OptNilModelField{
Set: true,
Null: true,
}
}
return OptNilModelField{
Value: *v,
Set: true,
}
} ResultThe above example could be refactored way easier: // This is returned from another abstracted layer, that doesn't know anything about http/openapi
servideModel := myService.ActionThatReturnsModel(...)
return &Model{
// Since the NewOptNil method takes a pointer, it automatically takes care of setting the value
// depending if Field is nil. No more errors, and the api feels more intuitive.
Field: NewOptNilModelField(servideModel.Field),
}, nil |
Description
Would it make more sense to instantiate
OptNilDateTime
(orOptDateTime
or any other optional type) by passing in a pointer?You would still have the flexibility to write more complex logic when you need it but it would simplify most uses cases.
The text was updated successfully, but these errors were encountered: