{"record":{"id":"89249507193ac650","repo":"pola-rs/polars","slug":"union-struct-must-be-created-with-the-correspondin","errorCode":null,"errorMessage":"Union struct must be created with the corresponding Union DataType","messagePattern":"Union struct must be created with the corresponding Union DataType","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/polars-arrow/src/array/union/mod.rs","lineNumber":192,"sourceCode":"        if let ArrowDataType::Union(u) = &dtype {\n            let fields = u\n                .fields\n                .iter()\n                .map(|x| new_null_array(x.dtype().clone(), length))\n                .collect();\n\n            let offsets = if u.mode.is_sparse() {\n                None\n            } else {\n                Some((0..length as i32).collect::<Vec<_>>().into())\n            };\n\n            // all from the same field\n            let types = vec![0i8; length].into();\n\n            Self::new(dtype, types, fields, offsets)\n        } else {\n            panic!(\"Union struct must be created with the corresponding Union DataType\")\n        }\n    }\n\n    /// Creates a new empty [`UnionArray`].\n    pub fn new_empty(dtype: ArrowDataType) -> Self {\n        if let ArrowDataType::Union(u) = dtype.to_storage() {\n            let fields = u\n                .fields\n                .iter()\n                .map(|x| new_empty_array(x.dtype().clone()))\n                .collect();\n\n            let offsets = if u.mode.is_sparse() {\n                None\n            } else {\n                Some(Buffer::default())\n            };\n","sourceCodeStart":174,"sourceCodeEnd":210,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-arrow/src/array/union/mod.rs#L174-L210","documentation":"`UnionArray::new_null` needs the union's field definitions and offset/type configuration from `ArrowDataType::Union(union_dtype)` to build the null child arrays and the all-zero types buffer. Any non-Union dtype cannot supply those components, so the constructor panics.","triggerScenarios":"Calling `UnionArray::new_null(dtype, length)` with a dtype that is not `ArrowDataType::Union` (checked via `dtype.to_storage()`).","commonSituations":"Generic array factories dispatching on runtime dtypes that feed a Union constructor the wrong variant, schema deserialization producing a flattened/incorrect dtype, or a Dense/Sparse union variable replaced by a different physical type during refactoring.","solutions":["Guard with `matches!(dtype.to_storage(), ArrowDataType::Union(_))` before calling `new_null`.","Use the generic `new_null_array(dtype, length)` dispatcher instead of the Union-specific constructor.","Fix the dtype source so a genuine Union dtype (with fields) is passed.","Convert the panic path into a Result in your own wrapper for user-facing error handling."],"exampleFix":"// before\nlet arr = UnionArray::new_null(dtype.clone(), length);\n// after\nlet arr = match dtype.to_storage() {\n    ArrowDataType::Union(_) => UnionArray::new_null(dtype.clone(), length),\n    _ => new_null_array(dtype.clone(), length),\n};","handlingStrategy":"validation","validationCode":"fn is_union_dtype(dtype: &ArrowDataType) -> bool {\n    matches!(dtype.to_storage(), ArrowDataType::Union(_))\n}","typeGuard":"fn as_union_dtype(dtype: &ArrowDataType) -> Option<&UnionDataType> {\n    match dtype.to_storage() {\n        ArrowDataType::Union(u) => Some(u),\n        _ => None,\n    }\n}","tryCatchPattern":"// check before construction:\nif as_union_dtype(&dtype).is_none() {\n    return Err(PolarsError::InvalidOperation(\"expected Union dtype\".into()));\n}\nlet arr = UnionArray::new_null(dtype, length);","preventionTips":["Route generic array creation through `new_null_array` instead of Union-specific constructors","Match on `to_storage()` when special-casing unions","Test dtype-dispatch code with Dense and Sparse union dtypes"],"tags":["rust","arrow","panic","union","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"}