@@ -329,6 +329,22 @@ impl std::fmt::Debug for UnionFields {
329329 }
330330}
331331
332+ /// Allows direct indexing into [`UnionFields`] to access fields by position.
333+ ///
334+ /// # Panics
335+ ///
336+ /// Panics if the index is out of bounds. Note that [`UnionFields`] supports
337+ /// a maximum of 128 fields, as type IDs are represented as `i8` values.
338+ ///
339+ /// For a non-panicking alternative, use [`UnionFields::get`].
340+ impl std:: ops:: Index < usize > for UnionFields {
341+ type Output = ( i8 , FieldRef ) ;
342+
343+ fn index ( & self , index : usize ) -> & Self :: Output {
344+ & self . 0 [ index]
345+ }
346+ }
347+
332348impl UnionFields {
333349 /// Create a new [`UnionFields`] with no fields
334350 pub fn empty ( ) -> Self {
@@ -396,6 +412,31 @@ impl UnionFields {
396412 self . 0 . iter ( ) . map ( |( id, f) | ( * id, f) )
397413 }
398414
415+ /// Returns a reference to the field at the given index, or `None` if out of bounds.
416+ ///
417+ /// This is a safe alternative to direct indexing via `[]`.
418+ ///
419+ /// # Example
420+ ///
421+ /// ```
422+ /// use arrow_schema::{DataType, Field, UnionFields};
423+ ///
424+ /// let fields = UnionFields::new(
425+ /// vec![1, 3],
426+ /// vec![
427+ /// Field::new("field1", DataType::UInt8, false),
428+ /// Field::new("field3", DataType::Utf8, false),
429+ /// ],
430+ /// );
431+ ///
432+ /// assert!(fields.get(0).is_some());
433+ /// assert!(fields.get(1).is_some());
434+ /// assert!(fields.get(2).is_none());
435+ /// ```
436+ pub fn get ( & self , index : usize ) -> Option < & ( i8 , FieldRef ) > {
437+ self . 0 . get ( index)
438+ }
439+
399440 /// Searches for a field by its type id, returning the type id and field reference if found.
400441 /// Returns `None` if no field with the given type id exists.
401442 pub fn find_by_type_id ( & self , type_id : i8 ) -> Option < ( i8 , & FieldRef ) > {
0 commit comments