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

fix(codegen): generate pointer types for nullable array items

Open putcho01 opened this issue 1 month ago • 4 comments

This PR adds capability to generate pointer types for nullable array items.

When an array's items have nullable: true, the generated Go type now correctly uses pointer types (e.g., []*float32 instead of []float32) to properly represent nullable values.

Ref Issue: #2016

Changes

  • Modified oapiSchemaToGoType() in pkg/codegen/schema.go to check the nullable property of array items
  • Added comprehensive test cases in internal/test/issues/issue-2016/ covering:
    • Primitive types (number, string, boolean, integer) with nullable items
    • Object types with nullable items
    • Nested arrays with nullable items
    • Nullable arrays with nullable items

Example

Input schema: Sample

  type: object
  required: [metrics]
  properties:
    metrics:
      type: array
      items:
        nullable: true
        type: number

Before (incorrect)

type Sample struct {
    Metrics []float32 `json:"metrics"`
}

After (correct)

type Sample struct {
    Metrics []*float32 `json:"metrics"`
}

putcho01 avatar Nov 22 '25 14:11 putcho01

Would using the Output Option prefer-skip-optional-pointer-on-container-types solve this?

jamietanna avatar Nov 22 '25 15:11 jamietanna

@jamietanna I don't think prefer-skip-optional-pointer-on-container-types would solve this issue, as they address different aspects

  • prefer-skip-optional-pointer-on-container-types: Controls pointer to the array itself (*[]string vs []string)
  • This fix: Controls pointer in array items when nullable ([]*string vs []string)

putcho01 avatar Nov 22 '25 15:11 putcho01

Gotcha, thanks - should we also be correctly using ,omitempty for the JSON tags in this case, too?

jamietanna avatar Nov 22 '25 17:11 jamietanna

@jamietanna I think the omitempty handling is already correct with this fix — it's determined by whether the property is required, which is independent of whether the array items are nullable.

That said, I want to make sure I understand your concern correctly. Were you thinking of a particular case where omitempty should behave differently when the array items are nullable?

putcho01 avatar Nov 22 '25 18:11 putcho01

Hi @jamietanna , just checking if you had a chance to look at my question above. Let me know what you think!

putcho01 avatar Dec 20 '25 07:12 putcho01