pola-rs/polars · error

StructArray must be initialized with DataType::Struct

Error message

StructArray must be initialized with DataType::Struct

What it means

`StructArray::new_empty` requires the passed `ArrowDataType` to be `DataType::Struct(fields)` because the empty array is built by creating an empty child array for each struct field. Any other dtype has no field list to iterate, so the constructor panics instead of returning a Result.

Solutions

  1. Match on the dtype before constructing: only call `new_empty` when the value is `ArrowDataType::Struct(_)`.
  2. Fix the dtype source (schema parsing, column metadata) so a Struct dtype is actually produced.
  3. Use a generic dispatcher such as `new_empty_array(dtype)` from the array module, which handles every dtype correctly.
  4. Return a proper error instead of panicking if the caller must handle bad dtypes gracefully.

Example fix

// before
let arr = StructArray::new_empty(dtype);
// after
let arr = match dtype.to_storage() {
    ArrowDataType::Struct(_) => StructArray::new_empty(dtype),
    _ => return Err(PolarsError::InvalidOperation(format!("expected Struct, got {:?}", dtype))),
};
Defensive patterns

Strategy: validation

Validate before calling

fn is_struct_dtype(dtype: &ArrowDataType) -> bool {
    matches!(dtype.to_storage(), ArrowDataType::Struct(_))
}

Type guard

fn as_struct_fields(dtype: &ArrowDataType) -> Option<&[ArrowField]> {
    match dtype.to_storage() {
        ArrowDataType::Struct(fields) => Some(fields),
        _ => None,
    }
}

Try / catch

// Rust panics are not catchable in safe code; validate before calling:
if as_struct_fields(&dtype).is_none() {
    return Err(PolarsError::InvalidOperation("expected Struct dtype".into()));
}
let arr = StructArray::new_empty(dtype);

Prevention

When it happens

Trigger: Calling `StructArray::new_empty(dtype)` with a non-Struct dtype such as `Utf8`, `Int32`, `List(..)`, or a plain (non-Struct) storage type.

Common situations: Generic array-building code that dispatches on a runtime dtype and assumes Struct, dtype strings parsed from config or schema files mapping to the wrong variant, or refactors where a variable that used to hold a Struct dtype now holds something else.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/33810420fc4647c6. Report an issue: GitHub.

Appendix: source

Thrown at crates/polars-arrow/src/array/struct_/mod.rs:134

    pub fn new(
        dtype: ArrowDataType,
        length: usize,
        values: Vec<Box<dyn Array>>,
        validity: Option<Bitmap>,
    ) -> Self {
        Self::try_new(dtype, length, values, validity).unwrap()
    }

    /// Creates an empty [`StructArray`].
    pub fn new_empty(dtype: ArrowDataType) -> Self {
        if let ArrowDataType::Struct(fields) = &dtype.to_storage() {
            let values = fields
                .iter()
                .map(|field| new_empty_array(field.dtype().clone()))
                .collect();
            Self::new(dtype, 0, values, None)
        } else {
            panic!("StructArray must be initialized with DataType::Struct");
        }
    }

    /// Creates a null [`StructArray`] of length `length`.
    pub fn new_null(dtype: ArrowDataType, length: usize) -> Self {
        if let ArrowDataType::Struct(fields) = &dtype {
            let values = fields
                .iter()
                .map(|field| new_null_array(field.dtype().clone(), length))
                .collect();
            Self::new(dtype, length, values, Some(Bitmap::new_zeroed(length)))
        } else {
            panic!("StructArray must be initialized with DataType::Struct");
        }
    }
}

// must use

View on GitHub (pinned to fe841f959e)