{"record":{"id":"33810420fc4647c6","repo":"pola-rs/polars","slug":"structarray-must-be-initialized-with-datatype-str","errorCode":null,"errorMessage":"StructArray must be initialized with DataType::Struct","messagePattern":"StructArray must be initialized with DataType::Struct","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/polars-arrow/src/array/struct_/mod.rs","lineNumber":134,"sourceCode":"    pub fn new(\n        dtype: ArrowDataType,\n        length: usize,\n        values: Vec<Box<dyn Array>>,\n        validity: Option<Bitmap>,\n    ) -> Self {\n        Self::try_new(dtype, length, values, validity).unwrap()\n    }\n\n    /// Creates an empty [`StructArray`].\n    pub fn new_empty(dtype: ArrowDataType) -> Self {\n        if let ArrowDataType::Struct(fields) = &dtype.to_storage() {\n            let values = fields\n                .iter()\n                .map(|field| new_empty_array(field.dtype().clone()))\n                .collect();\n            Self::new(dtype, 0, values, None)\n        } else {\n            panic!(\"StructArray must be initialized with DataType::Struct\");\n        }\n    }\n\n    /// Creates a null [`StructArray`] of length `length`.\n    pub fn new_null(dtype: ArrowDataType, length: usize) -> Self {\n        if let ArrowDataType::Struct(fields) = &dtype {\n            let values = fields\n                .iter()\n                .map(|field| new_null_array(field.dtype().clone(), length))\n                .collect();\n            Self::new(dtype, length, values, Some(Bitmap::new_zeroed(length)))\n        } else {\n            panic!(\"StructArray must be initialized with DataType::Struct\");\n        }\n    }\n}\n\n// must use","sourceCodeStart":116,"sourceCodeEnd":152,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-arrow/src/array/struct_/mod.rs#L116-L152","documentation":"`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.","triggerScenarios":"Calling `StructArray::new_empty(dtype)` with a non-Struct dtype such as `Utf8`, `Int32`, `List(..)`, or a plain (non-Struct) storage type.","commonSituations":"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.","solutions":["Match on the dtype before constructing: only call `new_empty` when the value is `ArrowDataType::Struct(_)`.","Fix the dtype source (schema parsing, column metadata) so a Struct dtype is actually produced.","Use a generic dispatcher such as `new_empty_array(dtype)` from the array module, which handles every dtype correctly.","Return a proper error instead of panicking if the caller must handle bad dtypes gracefully."],"exampleFix":"// before\nlet arr = StructArray::new_empty(dtype);\n// after\nlet arr = match dtype.to_storage() {\n    ArrowDataType::Struct(_) => StructArray::new_empty(dtype),\n    _ => return Err(PolarsError::InvalidOperation(format!(\"expected Struct, got {:?}\", dtype))),\n};","handlingStrategy":"validation","validationCode":"fn is_struct_dtype(dtype: &ArrowDataType) -> bool {\n    matches!(dtype.to_storage(), ArrowDataType::Struct(_))\n}","typeGuard":"fn as_struct_fields(dtype: &ArrowDataType) -> Option<&[ArrowField]> {\n    match dtype.to_storage() {\n        ArrowDataType::Struct(fields) => Some(fields),\n        _ => None,\n    }\n}","tryCatchPattern":"// Rust panics are not catchable in safe code; validate before calling:\nif as_struct_fields(&dtype).is_none() {\n    return Err(PolarsError::InvalidOperation(\"expected Struct dtype\".into()));\n}\nlet arr = StructArray::new_empty(dtype);","preventionTips":["Always match on `dtype.to_storage()` before dtype-specific constructors","Prefer generic helpers `new_empty_array`/`new_null_array` over type-specific constructors in generic code","Add unit tests for your dtype-dispatch layers"],"tags":["rust","arrow","panic","dtype"],"backgroundTag":"invalid-constructor-argument","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}