Skip to content

Commit c0fe5c4

Browse files
committed
Add first and first_mut methods
These are useful for getting an initial value when iterating over an array (e.g. when calculating the minimum element with `fold`).
1 parent 408f42b commit c0fe5c4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/impl_methods.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,29 @@ impl<A, S, D> ArrayBase<S, D> where S: Data<Elem=A>, D: Dimension
199199
}
200200
}
201201

202+
/// Returns a reference to the first element of the array, or `None` if it
203+
/// is empty.
204+
pub fn first(&self) -> Option<&A> {
205+
if self.is_empty() {
206+
None
207+
} else {
208+
Some(unsafe { &*self.as_ptr() })
209+
}
210+
}
211+
212+
/// Returns a mutable reference to the first element of the array, or
213+
/// `None` if it is empty.
214+
pub fn first_mut(&mut self) -> Option<&mut A>
215+
where
216+
S: DataMut,
217+
{
218+
if self.is_empty() {
219+
None
220+
} else {
221+
Some(unsafe { &mut *self.as_mut_ptr() })
222+
}
223+
}
224+
202225
/// Return an iterator of references to the elements of the array.
203226
///
204227
/// Elements are visited in the *logical order* of the array, which

0 commit comments

Comments
 (0)