diff --git a/arrow-schema/src/schema.rs b/arrow-schema/src/schema.rs index ede158fcf248..72ca56d7fbdc 100644 --- a/arrow-schema/src/schema.rs +++ b/arrow-schema/src/schema.rs @@ -331,10 +331,20 @@ impl Schema { /// Returns an immutable reference of a specific [`Field`] instance selected using an /// offset within the internal `fields` vector. + /// + /// Also consider using `try_field()` method with bounds check. pub fn field(&self, i: usize) -> &Field { &self.fields[i] } + /// Like `field()` but with bound check. + /// + /// Returns an immutable reference of a specific [`Field`] instance selected using an + /// offset within the internal `fields` vector. And `None` if the index is out of bounds. + pub fn try_field(&self, i: usize) -> Option<&Field> { + self.fields.get(i).map(|f| f.as_ref()) + } + /// Returns an immutable reference of a specific [`Field`] instance selected by name. pub fn field_with_name(&self, name: &str) -> Result<&Field, ArrowError> { Ok(&self.fields[self.index_of(name)?]) @@ -650,6 +660,13 @@ mod tests { schema.index_of("nickname").unwrap(); } + #[test] + fn schema_try_field() { + let schema = person_schema(); + assert!(schema.try_field(0).is_some()); + assert!(schema.try_field(99999).is_none()); + } + #[test] #[should_panic( expected = "Unable to get field named \\\"nickname\\\". Valid fields: [\\\"first_name\\\", \\\"last_name\\\", \\\"address\\\", \\\"interests\\\"]"